12

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

4 Answers 4

22

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})
2
  • thanks for tip. What a handy contrib. I have made a custom oauth2 authentication as a learning exercise, and passing back an error was the last thing I had to do. Django 2.2 Dec 30, 2020 at 1:25
  • Very helpful. In my case I needed more integration with bootstrap4 and found this reference which is quite helpful to get the alerts "right". In your solution, they are only of one colour, no really reflective of the severity of the message. ordinarycoders.com/blog/article/django-messages-framework
    – mjn
    Feb 18, 2022 at 22:19
20

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 %}
3
  • 1
    This seems like the simplest solution that integrates easily with the default login views Django provides. +1 Jun 18, 2018 at 19:48
  • 1
    How exactly does form.errors work? Does Django re-render the form with form.errors being present?
    – timbram
    Jun 28, 2018 at 17:37
  • @MLavrentyev And definitely agree.
    – timbram
    Jun 28, 2018 at 17:39
4

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.

1
  • 1
    Your explanation regarded to non-field errors is awesome! Thanks. Mar 3, 2021 at 18:23
1

You already have {{ form.as_p }} in your template, so Django will show any form errors.

The problem is that the AuthenticationForm takes request as its first argument. You can then use form.is_valid() to check whether the username and password are valid and that the user is active, instead of fetching the data from request.POST manually.

def login(request):
    if request.method == 'POST':
        form = AuthenticationForm(request, request.POST)
        if form.is_valid():
            auth_login(self.request, form.get_user())
            return redirect('index')
    else:
        form = AuthenticationForm(request)
    return render(request, 'todo/login.html', {'form': form})

Another option would be to use the built-in LoginView instead of writing your own:

from django.contrib.auth import views as auth_views

urlpatterns = [
    ...
    path('accounts/login/', auth_views.LoginView.as_view(template_name='todo/login.html')),
    ...
]

Then set LOGIN_REDIRECT_URL in your settings.

LOGIN_REDIRECT_URL = 'index'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.