DEV Community

nūh ben
nūh ben

Posted on

Django LoginView and flash messages

The strory

Today I was working on an authentication system with Django, so I created a function based view that handles users registration, once the registration is complete it makes sense to redirect the users somewhere else typically a login page and notify them with a flash message (an alert on the front-end) to tell them what is going on. This was easily achieved by combining django flash messages and bootstrap alerts, but when I wanted to to use the same approach for the login part, I struggled because for login in the users I used the pre-built django class LoginView.

The solution

The trick was to use my own login view that extends the django default LoginView and also uses the django messages mixins:

views.py

from django.contrib.messages.views import SuccessMessageMixin
from django.contrib.auth.views import LoginView
class MyLoginView(SuccessMessageMixin ,LoginView):
    template_name = 'users/login.html'
    success_url = 'blog-home'
    success_message = 'Welcome to your profile'

On the template, it is best to display the messages on the base template so we are sure they would be seen where ever the user is right now.

templates.html

<div class="col-10 ml-auto>
   {% if messages %}
       {% for message in messages %}
          <div class="row justify-content-end">
             <div class="col-4 text-center">
                 <div class="alert alert-{{message.tags}}">
                         {{ message }}
                 </div>
              </div>
           </div>
        {% endfor %}
   {% endif%}
</div>

Top comments (1)

Collapse
 
umair313 profile image
Umair Mehmood (TheFatBoy)

I am facing issues in showing form field error when form is return by LoginView in case of wrong credentials do you have any idea I am not using bootsrap