2014-03-25 63 views
0

我在的log in的下面找到以下這段代碼:code。 我在下面有不同的版本,我想知道它是否與上述不同。在Django中的用戶認證?

我做了一個if request.user檢查。只有在authenticated/logged正確時,user纔會附加到request

documentation

from django.contrib.auth import authenticate, login 

def my_view(request): 
    username = request.POST['username'] 
    password = request.POST['password'] 
    user = authenticate(username=username, password=password) 
    if user is not None: 
     if user.is_active: 
      login(request, user) 
      # Redirect to a success page. 
     else: 
      # Return a 'disabled account' error message 
    else: 
     # Return an 'invalid login' error message. 

my version:

from django.contrib.auth import authenticate, login 

    def my_view(request): 
     if request.user: 
     if user.is_active: 
      login(request, user) 
      # Redirect to a success page. 
     else: 
      # Return a 'disabled account' error message 
    else: 
     # Return an 'invalid login' error message. 
+2

如果用戶未登錄,request.user將爲'AnonymousUser'。在您的版本中,您不會驗證用戶輸入的用戶名和密碼是否正確。你可以通過'request.user.is_authenticated()'來檢查用戶是否被綁定。 – karthikr

回答

0

有兩個版本之間的巨大差異。

docs

If the current user has not logged in, this attribute will be set to an 
instance of AnonymousUser, otherwise it will be an instance of User. 

,所以你會想:

if request.user.is_authenticated(): 
    # Do something for authenticated users. 
else: 
    # Do something for anonymous users.