2017-04-03 23 views
2

這是我的用戶身份驗證方法:Django的 - 用戶IS_ACTIVE

def user_login(request): 
    if request.method == 'POST': 
     username = request.POST.get('username') 
     password = request.POST.get('password') 
     user = authenticate(username=username, password=password) 

     if user: 
      if user.is_active: 
       login(request, user) 
       return HttpResponseRedirect(reverse('index')) 
      else: 
       print('TEST') 
       messages.info(request, 'Inactive user') 
       return HttpResponseRedirect(reverse('index')) 
     else: 
      messages.error(request, 'Invalid username/password!') 
     return HttpResponseRedirect(reverse('index')) 
    else: 
     return render(request, 'mainapp/login.html', {}) 

如果用戶存在和不活躍出現錯誤信息:

messages.error(request, 'Invalid username/password!') 
return HttpResponseRedirect(reverse('index')) 

代替:

print('TEST') 
messages.info(request, 'Inactive user') 
return HttpResponseRedirect(reverse('index')) 

我不知道這裏有什麼問題......任何線索?

+0

你試過用戶不是沒有嗎? –

+0

是的,我試過了。 – jundymek

+0

Django帶有[認證視圖](https://docs.djangoproject.com/zh/1.10/topics/auth/default/#module-django.contrib.auth.views),包括登錄視圖。你不必自己寫! – Alasdair

回答

6

默認ModelBackend身份驗證後端開始拒絕Django 1.10中的非活動用戶。因此您的authenticate()呼叫返回None,並且您得到無效的用戶名/密碼!來自外部if/else語句的消息。按照Daniel的說法,如果您使用默認的ModelBackend,則不再需要在登錄視圖中檢查user.is_active

如果您真的想讓authenticate返回非活動用戶,那麼您可以使用AllowAllUsersModelBackend代替。如果您這樣做,那麼您有責任在登錄視圖中檢查is_active標誌。

AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.AllowAllUsersModelBackend'] 
4

authenticate的調用已經檢查用戶是否設置了is_active標誌,如果不是,則返回None。無需單獨檢查。

+0

然後我如何檢查用戶是否存在但是不活動? – jundymek

+1

你爲什麼想要? –

+0

我剛剛學習Django,並且因爲有「is_active」標誌,我想知道如何使用它。 – jundymek