2017-03-04 42 views
2

我想使用AuthenticationForm模型來認證我的用戶。在Django中使用AuthenticationForm返回沒有錯誤

這是我的觀點:

from django.contrib.auth.forms import AuthenticationForm 

def connection(request): 
    if request.user.is_authenticated(): 
     return redirect('user:profile') 

    if request.method == "POST": 
     connection_form = AuthenticationForm(request.POST) 
     if connection_form.is_valid(): 
      username = connection_form.cleaned_data["username"] 
      password = connection_form.cleaned_data["password"] 
      user = authenticate(username=username, password=password) 
      if user is not None: 
       login(request, user) 
       if next is not None: 
        return redirect(next) 
       else: 
        return redirect('home') 
    else : 
     connection_form = AuthenticationForm() 
    return render(request, 'user/connection.html', { 'connection_form': connection_form }) 

這裏是我的模板代碼:

<form action="{% url 'user:connection' %}{% if request.GET.next %}?next={{request.GET.next}}{% endif %}" method="post"> 
    {% csrf_token %} 
    {{ connection_form }} 
    <input type="submit" value="Se connecter" /> 
</form> 

它幾乎工作。但是我的問題是,當用戶名和/或密碼不正確時,表單不會返回任何錯誤。

當我嘗試這在shell它的工作原理

>>> POST = {'username' : 'test', 'password' : 'me', } 
>>> form = AuthenticationForm(data=POST) 
>>> form.is_valid() 
False 
>>> form.as_p() 
'<ul class="errorlist nonfield"><li>Please enter a correct username and password. Note that both fields may be case-sensitive.</li></ul>\n<p><label for="id_username">Username:</label> <input autofocus="" id="id_username" maxlength="254" name="username" type="text" value="test" required /></p>\n<p><label for="id_password">Password:</label> <input id="id_password" name="password" type="password" required /></p>' 

任何想法?

+0

如果代碼在shell中工作,但不在正在生成的網頁中,則可能是模板問題。你能發佈你的模板代碼嗎? –

+0

我只是把它添加到我原來的文章 – manuk

回答

1

AuthenticationForm表現與常規形式有點不同,它需要一個data參數。您的shell代碼中有data參數,但不在您的視圖中。它應該是:

connection_form = AuthenticationForm(data=request.POST) 
+0

謝謝!有用 – manuk

相關問題