0

我在Django中遇到了authenticating用戶名和密碼這兩種方式。 這是首選方法,爲什麼?在Django中驗證用戶登錄的更好方法?

方式一:

from django.contrib.auth import authenticate, login, logout 

if request.method == 'POST': 
       form = LoginForm(request.POST) 
       if form.is_valid(): 
         username = form.cleaned_data['username'] 
         password = form.cleaned_data['password'] 
         drinker = authenticate(username=username, password=password) 
         if drinker is not None: 
           login(request, drinker) 
           return HttpResponseRedirect('/profile/') 

其他方式:

from django.contrib.auth.backends import ModelBackend 

class MyModelBackend(ModelBackend): 
    def authenticate(self, username=None, password=None): 
     print "My Logic" 
     return super(MyModelBackend, self).authenticate(username=username, password=password) 

回答

1

如果註冊自定義的後端,在你看來調用authenticate將針對MyModelBackend

Django的認證嘗試在其所有身份驗證後端進行身份驗證。 如果第一種身份驗證方法失敗,則Django會嘗試第二種身份驗證方法,即 等等,直到嘗試完所有後端爲止。

documentation的例子,也表明MyModelBacked需要實現一個get_user方法以及

我相信,在documentation清楚地解釋了什麼是子類ModelBackend做,以及如何做到這一點成功