密码不会设置

时间:2016-02-19 06:34:41

标签: python django

我已经制作了自定义用户模型和管理员但是我无法在我的注册表单中获取密码。没有显示错误,但是当我查看管理面板时,它显示"没有设置密码。"。谁能在我的代码中看到我做错了什么?干杯

模特 -

class CustomUserManager(BaseUserManager):

    def _create_user(self, email, password1, is_staff, is_superuser, **extra_fields):
        now = timezone.now()
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email=email,
                          is_staff=is_staff, is_active=True,
                          is_superuser=is_superuser, last_login=now,
                          date_joined=now, **extra_fields)
        user.set_password(password1)
        user.save(using=self._db)
        return user

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

    def create_superuser(self, email, password, **extra_fields):
        return self._create_user(email, password, True, True,
                                 **extra_fields)

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField('email address', unique=True)
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    is_staff = models.BooleanField('staff status', default=False,
        help_text='Designates whether the user can log into this admin site.')
    is_active = models.BooleanField('active', default=True,
        help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.')
    date_joined = models.DateTimeField('date joined', default=timezone.now)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
    objects = CustomUserManager()

    class Meta:
        verbose_name = 'user'
        verbose_name_plural = 'users'

    def get_full_name(self):
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        return self.first_name

    def email_user(self, subject, message, from_email=None):
        send_mail(subject, message, from_email, [self.email])

表格 -

class UserForm(forms.ModelForm):

    email = forms.EmailField()
    password1 = forms.CharField(
        label=("Password"),
        widget=forms.PasswordInput)
    password2 = forms.CharField(
        label=("Password confirmation"),
        widget=forms.PasswordInput,
        help_text=("Enter the same password as above, for verification."))

    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'email', 'password1', 'password2']

    def clean_password2(self):
        password1 = self.cleaned_data.get("password")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise ValidationError("Both Passwords must match!")

建议错误 -

Unhandled exception in thread started by <function wrapper at 0x0000000003D60668>
Traceback (most recent call last):
  File "C:\Python27\Lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "C:\Python27\Lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run
    autoreload.raise_last_exception()
  File "C:\Python27\Lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception
    six.reraise(*_exception)
  File "C:\Python27\Lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "C:\Python27\Lib\site-packages\django\__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Python27\Lib\site-packages\django\apps\registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "C:\Python27\Lib\site-packages\django\apps\config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module
    __import__(name)
  File "D:\Other folders\Desktop\Student Job Search\code\opus_jobs_project\profiles\models.py", line 2, in <module>
    from opus_login.models import User
  File "D:\Other folders\Desktop\Student Job Search\code\opus_jobs_project\opus_login\models.py", line 43, in <module>
    class User(AbstractBaseUser, PermissionsMixin):
  File "C:\Python27\Lib\site-packages\django\db\models\base.py", line 223, in __new__
    'base class %r' % (field.name, name, base.__name__)
django.core.exceptions.FieldError: Local field 'password' in class 'User' clashes with field of similar name from base class 'AbstractBaseUser'

1 个答案:

答案 0 :(得分:1)

要手动为用户设置密码,您需要调用set_password方法。首先,在save类中创建UserForm方法。

class UserForm(forms.ModelForm):
    # your code ...
    # ...

    def save(self, commit=True):
        user = super(UserForm, self).save(commit=False)
        user.set_password(self.cleaned_data['password2'])

        if commit:
            user.save()
        return user