Django身份验证不返回现有用户

时间:2018-11-27 10:29:22

标签: python django django-forms

我的forms.py:

class UserLoginForm(forms.Form):
 username = forms.CharField(widget=forms.TextInput(attrs= 
 {'class':'form-control form-control-lg','placeholder':'Username'}))
  password = forms.CharField(widget=forms.PasswordInput(attrs= 
 {'class':'form-control form-control-lg','placeholder':'Password'}))

  def clean(self, *args, **kwargs):
     username = self.cleaned_data.get("username")
     password = self.cleaned_data.get("password")

     if username and password:
         user = authenticate(username=username, password=password)

         if user is None:
             raise forms.ValidationError("This user does not exist")
         elif user is not None:
            if not user.is_active:
                raise forms.ValidationError("This user is not longer 
          active.")

            elif not user.check_password(password):
                raise forms.ValidationError("Incorrect password")

    return super(UserLoginForm, self).clean(*args, **kwargs)

models.py:

class User(AbstractUser):
 is_client = models.BooleanField(default=False)
 is_trainer = models.BooleanField(default=False)
 username = models.CharField('username', max_length=150, unique=True)
 email = models.EmailField(unique=True)
 hub = models.ForeignKey(Hub, on_delete=models.CASCADE,blank=True, 
 null=True)
 USER_POSITIONS = ((0, 'Not a member'), (1, 'Member'), (2, 'Excom'), 
 (3, 'Leader'))
 hub_position = models.CharField(default='Not Member',max_length=50)
 mentor = models.ForeignKey('self' ,on_delete=models.CASCADE, 
 blank=True,null=True)
 terms = models.BooleanField(blank=True,default=False)
 USERNAME_FIELD = 'username'
 REQUIRED_FIELDS = ['email','terms']

 def get_absolute_url(self):
     return reverse('student:dashboard', kwargs={'pk': self.pk})

如果用户尚未激活,我希望将其重定向到重新发送激活链接页面。现在,在我注册该用户并跳过帐户激活然后尝试登录之后,尽管显示验证错误“该用户不存在”该用户已在用户模型中注册。

1 个答案:

答案 0 :(得分:1)

问题在于您使用的Django版本。

仅当user.is_active=TRUE

时,最新版本的Django才会为用户返回任何身份验证

我建议您为CustomUserModel使用User

我使用这样的东西:

class User(AbstractBaseUser):
    email = models.EmailField(db_index=True, unique=True, max_length=255)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']
    objects = UserManager()

    def __str__(self):
        return self.email

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

def has_module_perms(self, app_label):
    return True

并在我的AUTH_USER_MODEL = 'myapp.User'中添加settings.py

基本上,选择适合您需求的CustomUserModel