Skip to main content
 首页 » 编程设计

python之在 Django 中使用 AuthenticationForm 不返回任何错误

2024年10月01日36jiqing9006

我正在尝试使用 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>' 

有什么想法吗?

请您参考如下方法:

AuthenticationForm 的行为与常规表单有点不同,它需要一个 data 参数。您的 shell 代码中有 data 参数,但您的 View 中没有。应该是:

connection_form = AuthenticationForm(data=request.POST)