2017-08-09 444 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") 
相關問題