Python 如何在Django中阻止具有特定状态的用户登录
我正在使用Django 1.11和基于类的视图。 我的用户模型是定制的,它有一个Python 如何在Django中阻止具有特定状态的用户登录,python,django,django-login,Python,Django,Django Login,我正在使用Django 1.11和基于类的视图。 我的用户模型是定制的,它有一个状态字段,其中有“启用、阻止和禁用”。我想知道我如何才能只允许用户登录,而其他用户则被禁止 谢谢 您可以执行以下操作来检查用户状态是否已启用 from django.views.generic import View class LoginView(View): def post(self, request): username = request.POST['username']
状态
字段,其中有“启用、阻止和禁用”。我想知道我如何才能只允许用户登录,而其他用户则被禁止
谢谢 您可以执行以下操作来检查用户
状态
是否已启用
from django.views.generic import View
class LoginView(View):
def post(self, request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.status == 'enabled': # checking if user is "enabled"
login(request, user)
return HttpResponseRedirect('/form')
else:
return HttpResponse("Disabled user.")
else:
return HttpResponseRedirect(settings.LOGIN_URL)
return render(request, "index.html")
您可以执行以下操作来检查用户的
状态
是否已启用
from django.views.generic import View
class LoginView(View):
def post(self, request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.status == 'enabled': # checking if user is "enabled"
login(request, user)
return HttpResponseRedirect('/form')
else:
return HttpResponse("Disabled user.")
else:
return HttpResponseRedirect(settings.LOGIN_URL)
return render(request, "index.html")
您可以覆盖默认窗体 forms.py
from django.contrib.auth.forms import AuthenticationForm
class AuthenticationFormWithChekUsersStatus(AuthenticationForm):
def confirm_login_allowed(self, user):
if not user.status == 'enabled':
raise forms.ValidationError(
("Your account has disabled."),
code='inactive',
)
在您的URL中,它可以是:
from forms import AuthenticationFormWithChekUsersStatus
url(r'^login/$', auth_views.LoginView.as_view(authentication_form=AuthenticationFormWithChekUsersStatus)),
更多详细信息:您可以覆盖默认表单 forms.py
from django.contrib.auth.forms import AuthenticationForm
class AuthenticationFormWithChekUsersStatus(AuthenticationForm):
def confirm_login_allowed(self, user):
if not user.status == 'enabled':
raise forms.ValidationError(
("Your account has disabled."),
code='inactive',
)
在您的URL中,它可以是:
from forms import AuthenticationFormWithChekUsersStatus
url(r'^login/$', auth_views.LoginView.as_view(authentication_form=AuthenticationFormWithChekUsersStatus)),
更多详细信息:每当
用户尝试登录时,请检查他们的状态
在您对他们的用户名和密码进行身份验证后也会被启用。如何使用基于类的视图执行此操作?显示一些代码,即您的视图和模型。顺便说一句,您可以在执行身份验证的地方执行所有检查。我唯一需要的是每次用户登录时都要验证它是否“已启用”。此状态是用户模型中的枚举。我曾考虑过覆盖身份验证,但我不知道如何覆盖,或者是否有更简单、更正确的方法。跟随帐户应用程序:每次用户
尝试登录时,您都可以参考,检查他们的状态
在您验证他们的用户名和密码后是否已启用。如何使用基于类的视图执行此操作?显示一些代码,即您的视图和模型。顺便说一句,您可以在执行身份验证的地方执行所有检查。我唯一需要的是每次用户登录时都要验证它是否“已启用”。此状态是用户模型中的枚举。我曾考虑过覆盖身份验证,但我不知道如何覆盖,或者是否有更简单、更正确的方法。跟随帐户应用程序:您可以参考