Skip to content
Advertisement

Django login messages not being delivered as expected

I’m building a Django project and I have a Django app for the login, which I called members. The project is behind the login, so all the URLs redirect to the login page if the user is not logged.

If the user inputs an existing user and password, the user can access to the site. This workd OK.

If the credentials are wrong, I want the app to send back a message to the user, something like “Your credentials are wrong, try again”, but I’m not getting this to work, even if I copied and pasted from the official documentation.

My view:

def login_user(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request, username=username, password=password)
    if user is not None:
        login(request, user)
    else:
        messages.error(request, 'Credenciales inválidas.')

My base template, which other template extends:

{% load static %}

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Mapa Primera Infancia: Login</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" type="text/css" href="{% static 'login.css' %}" />
  </head>
  <body>

  <div class="msg">

    {% for message in messages %}
    <div class="alert alert-info">{{message}}</div>
{% endfor %}

  </div>

  {% block content %}
  {% endblock %}

</body>
</html>

URLs of the members app:

urlpatterns = [
    path('login_user/', views.login_user, name='login'),
]

I don’t know what is wrong and how to debug this. I suspect the problem is not in the template but in the response.

Any hints?

I’m working on Django 3.2.5

Advertisement

Answer

Finally, managed to get this done by myself. The error was that the templates in the members app were saved under templates/registration instead of templates/aunthenticate.

Advertisement