Django -rest-framework: разные - django .db.utils.IntegrityError: Сбой ограничения NOT NULL: account_user.password - PullRequest
0 голосов
/ 04 мая 2020

Я использую django -rest-auth для аутентификации. Регистрация, вход в систему, выход из системы работают должным образом, но когда я пытаюсь отредактировать данные пользователя через панель администратора, поле пароля ведет себя как необязательное поле, и при этом это не обнуляемое поле и поэтому выдает мне следующую ошибку. Что-то не так в коде, пожалуйста, помогите мне с этим.

models.py

class CustomUserManager(BaseUserManager):


    def _create_user(self,username, email, password, is_staff,is_admin, is_superuser, **extra_fields):
        if not email:
            raise ValueError('Users must have an email address')
        if not username:
            raise ValueError('Users must have an username')

        now = timezone.now()
        email = self.normalize_email(email)

        user = self.model(
            email=email,
            username=username,
            is_staff=is_staff,
            is_active=True,
            is_admin=is_admin,
            is_superuser=is_superuser,
            last_login=now,
            date_joined=now,
            **extra_fields
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self,username, email, password=None, **extra_fields):
        return self._create_user( username, email, password, False, False, False, **extra_fields)

    def create_staff(self,username, email, password, **extra_fields):
        user = self._create_user( username,email, password,  True, False, False, **extra_fields)
        user.save(using=self._db)
        return user

    def create_admin(self,username, email, password, **extra_fields):
        user = self._create_user( username,email, password,  True, True, False, **extra_fields)
        user.save(using=self._db)
        return user

    def create_superuser(self,username, email, password, **extra_fields):
        user = self._create_user( username,email, password,  True, True, True, **extra_fields)
        user.save(using=self._db)
        return user

class User(AbstractBaseUser):
    username = CharField(_('username'), max_length=100,unique=True)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
    email = EmailField(_('email address'), unique=True)
    is_staff = BooleanField(default=False)
    is_admin = BooleanField(default=False)                                                                                                                                                    
    is_active = BooleanField(default=True)
    is_superuser = BooleanField(default=False)
    last_login = DateTimeField(auto_now=True)
    date_joined = DateTimeField(auto_now_add=True)
    full_name = CharField(_("Full Name"), max_length=50, null=True)
    date_of_birth = DateField( auto_now=False, auto_now_add=False, null=True)
    is_verified = BooleanField(_("Verified"), default=False)
    gender = CharField(_("Gender"), max_length=6, choices=GENDER_CHOICES,null=True)

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    objects = CustomUserManager()

    def __str__(self):
        return self.username

    def has_perm(self,perm,obj=None):
        return self.is_admin

    def has_module_perms(self,app_label):
        return True

serializer.py

class RegisterSerializer(RegisterSerializer):
    full_name = serializers.CharField()
    date_of_birth = serializers.DateField()
    is_verified = serializers.BooleanField(read_only=True,default=False)


    def get_cleaned_data(self):
        super(RegisterSerializer, self).get_cleaned_data()
        return {
            'username': self.validated_data.get('username', ''),
            'password1': self.validated_data.get('password1', ''),
            'email': self.validated_data.get('email', ''),
            'full_name': self.validated_data.get('full_name', ''),
            'date_of_birth': self.validated_data.get('date_of_birth', ''),
            'is_verified': self.validated_data.get('is_verified', ''),
        }

admin.py

class UserCreationForm(forms.ModelForm):

    password = forms.CharField(label='Password', widget=forms.PasswordInput, required=True)
    #password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ( 'email','username','password','full_name','date_of_birth','is_verified')

    def clean_password(self):
        # Check that the two password entries match
        password = self.cleaned_data.get("password")
        # password2 = self.cleaned_data.get("password2")
        # if password1 and password2 and password1 != password2:
        #     raise forms.ValidationError("Passwords don't match")
        return password

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password"])
        if commit:
            user.save()
        return user


class UserChangeForm(forms.ModelForm):

    password = ReadOnlyPasswordHashField()

    class Meta:
        model = User
        fields = ('email','username','password','full_name','date_of_birth','is_verified', 'is_active', 'is_admin')

    def clean_password(self):
    #     # Check that the two password entries match
        password = self.cleaned_data.get("password")
    #     # password2 = self.cleaned_data.get("password2")
    #     # if password1 and password2 and password1 != password2:
    #     #     raise forms.ValidationError("Passwords don't match")
        return password


class UserAdmin(BaseUserAdmin):
    # The forms to add and change user instances
    form = UserChangeForm
    add_form = UserCreationForm


    list_display = ('username','email','password','full_name','date_of_birth','is_verified' )
    list_filter = ('is_staff','is_admin','is_superuser')
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Personal info', {'fields': ('username','full_name','date_of_birth','is_verified')}),
        ('Permissions', {'fields': ('is_staff','is_admin','is_superuser')}),
    )

    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'username', 'password'),
        }),
    )
    search_fields = ('username',)
    ordering = ('-username',)
    filter_horizontal = ()

admin.site.register(User, UserAdmin)

Спасибо

...