SJ19 SJ19 - 7 months ago 105
HTTP Question

Python/Django: How to display error messages on invalid login?

I'm trying to do the Login for my Django (2.0) website, so far I've got the login working for existing accounts. I'm using the built-in login function.

Now I want to display an error message when you enter an invalid account, for example "Invalid username or password!". But I have no idea how to go about this.

Right now it just refreshes the login page when your enter an invalid account. Any help is appreciated!

Login.html

{% block title %}Login{% endblock %}

{% block content %}
<h2>Login</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
{% endblock %}


Login view

def login(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)

if user is not None:
if user.is_active:
auth_login(request, user)
return redirect('index')

else:
form = AuthenticationForm()
return render(request, 'todo/login.html', {'form': form})

Answer Source

in your template

   {% for message in messages %}

                    <div class="alert alert-success">
                        <a class="close" href="#" data-dismiss="alert">×</a>

                        {{ message }}

                    </div>
            {% endfor %}

in view

from django.contrib import messages

def login(request):
    if request.method == 'POST':
        form = AuthenticationForm(request.POST)
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)

        if user is not None:
            if user.is_active:
                auth_login(request, user)
                return redirect('index')
        else:
            messages.error(request,'username or password not correct')
            return redirect('login')

    else:
        form = AuthenticationForm()
    return render(request, 'todo/login.html', {'form': form})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download