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

Updating for Django 2.0:

For individual field errors (e.g) :

    <input type="text" class="form-control my-4" id="id_username" placeholder="Username" name="username">

    {% for error in form.username.errors %}
         <p class="text-danger">{{ error }}</p>
    {% endfor %}

For non field errors (e.g if password is incorrect):

     {% if form.non_field_errors %}
            {% for error in form.non_field_errors %}
                <p class="text-danger">{{ error }}</p>
            {% endfor %}
      {% endif %}

You should place the above at the end of all fields.


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

You should just add inside your template:

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

{% block content %}
<h2>Login</h2>

{% if form.errors %}
    <p>username or password not correct</p>
{% endif %}

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