2012-11-03 44 views
1

我正在嘗試使用django內置的AuthenticationForm來允許用戶使用他們的電子郵件地址和密碼進行登錄。我已更改身份驗證功能以接受用戶名和電子郵件來驗證用戶身份。如何使用django內置的表單?

這是我到目前爲止的代碼:

 def loginuser(request): 
      if request.POST: 
      """trying to use AuthenticationForm to login and add validations""" 
      form = AuthenticationForm(request.POST.get('email'),request.POST.get('password')) 
      user = form.get_user() 
      if user.is_active: 
       login(request,user) 
       render_to_response('main.html',{'user':user}) 
      else: 
       HttpResponse('user not active') 
      render_to_response('login.html') 

但這並不是如何認證形式使用,至少不正確的方法。

回答

0

一個例子。你可以看到django.contrib.auth.forms出軌(在forms.py文件中搜索AuthenticationForm)。

f = AuthenticationForm({ 'username': request.POST.get('email'), 'password': request.POST.get('password') }) 
try: 
    if f.is_valid(): 
     login(f.get_user()) 
    else: 
     # authentication failed 
except ValidationError: 
    # authentication failed - wrong password/login or user is not active or can't set cookies. 

因此,修改代碼以:

def loginuser(request): 
     if request.POST: 
     """trying to use AuthenticationForm to login and add validations""" 
     form = AuthenticationForm(request.POST.get('email'),request.POST.get('password')) 
     try: 
      if form.is_valid(): 
       # authentication passed successfully, so, we could login a user 
       login(request,form.get_user()) 
       render_to_response('main.html',{'user':user}) 
      else: 
       HttpResponse('authentication failed') 
     except ValidationError: 
      HttpResponse('Authentication failed - wrong password/login or user is not active or can't set cookies') 

     render_to_response('login.html') 
+0

不會在沒有被調用POST方法的最後一行被執行? – heaven00

+0

@ user1702796是的,你是對的。它可能會被執行。 – sergzach

相關問題