Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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})
like image 438
SJ19 Avatar asked Dec 21 '17 11:12

SJ19


2 Answers

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 %}
like image 124
Mike Ru Avatar answered Nov 15 '22 21:11

Mike Ru


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})
like image 19
Exprator Avatar answered Nov 15 '22 23:11

Exprator