我有一个我正在玩的自定义身份验证后端。我想允许非活动用户登录。将supports_inactive_user
标志设置为true似乎不起作用,即使我可以验证是否正在返回user
。
class AuthenticationBackend(ModelBackend):
supports_object_permissions = False
supports_anonymous_user = True
supports_inactive_user = True
def authenticate(self, username=None, password=None):
"""
Allow login with email inplace of username
"""
user = None
if username is not None:
username = username.strip()
if email_re.search(username):
try:
user = User.objects.get(email__iexact=username)
except User.DoesNotExist:
pass
if not user:
try:
user = User.objects.get(username__iexact=username)
except User.DoesNotExist:
return None
if user.check_password(password):
return user
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
我正在使用django 1.4。我错过了什么?
答案 0 :(得分:1)
您的用户已成功通过身份验证,但当用户处于非活动状态时,AuthenticationForm
会引发ValidationError
。您可以覆盖子类中的clean方法以捕获相应的ValidationError
:
class InactiveAuthenticationForm(AuthenticationForm):
# a bit messy but it should work
def clean(self):
try:
return super(InactiveAuthenticationForm, self).clean()
except ValidationError as e:
if self.cached_user is not None: # user exists but is not active
# behavior that's skipped because of the validation error
self.check_for_test_cookie()
return self.cleaned_data
else:
raise e
但是,请考虑用户的is_active
标志是实际删除用户的替代标志。您可能想重新考虑使用is_active
。如果您希望用户在创建帐户后能够立即登录,那么有更好的方法可以实现这一目标。