manuk
manuk

Reputation: 51

the using of AuthenticationForm in django return no errors

I'm trying to use the AuthenticationForm model to authenticate my users.

Here is my view :

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 })

here is my template code :

<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>

It almost works. But my problem is that no errors are returned by the form when the username and/or the password are incorrect.

When i try this in the shell it works

>>> 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>'

Any ideas?

Upvotes: 2

Views: 1081

Answers (1)

Adrian Ghiuta
Adrian Ghiuta

Reputation: 1619

AuthenticationForm behaves a bit different from regular forms, it needs a data argument. You have the data argument in your shell code, but not in your view. It should be:

connection_form = AuthenticationForm(data=request.POST)

Upvotes: 3

Related Questions