2017-08-09 445 views
0

我使用的是基于类的Django 1.11和视图。 我的用户模型是自定义的,它有一个status字段,它具有“启用,禁用和禁用”。我想知道我只能让用户登录,其他人不能登录。如何在Django中以某些状态阻止用户登录

谢谢!

+0

每次'用户'试图登录时,检查他们的'status'是否启用以及'认证'他们的用户名和密码。 – Bijoy

+0

我该如何使用基于类的视图来做到这一点? –

+0

显示您的一些代码,即您的视图和模型。顺便说一句,你可以做所有的检查你正在执行'认证'。 – Bijoy

回答

0

可以覆盖默认形式,

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', 
      ) 

而在你的网址,就可以了如:

from forms import AuthenticationFormWithChekUsersStatus 

url(r'^login/$', auth_views.LoginView.as_view(authentication_form=AuthenticationFormWithChekUsersStatus)), 

更多详细信息:all-authentication-views

0

你可以做以下检查,如果用户statusenabled

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") 
相关问题