How can you output something when login is completed? Django

Viewed 133

I'm trying to build a form that when the login button is clicked, it displays a login succesful message. Here is the thing, I want that when the "login" button is clicked, the user gets redirected and in the redirected page (which is the home page), it should show the message. How can you do this in Django?

I've tried doing:

{% if request.user.is_authenticated %}

But the problem with this code is that the message appears each time, even when you reload the page.

3 Answers

Django Messages framework is a great simple way to show a one-time message to the user.

In a FormView, a message might look like this:

from django.contrib import messages

class MyFormView(FormView):

    def get_success_url(self):
        messages.success(self.request, 'Thank you. We will contact you as soon as we can.')
        return reverse('contact')

You can render a message in the template like this:

{% if messages %}
        {% for message in messages %}
            <p>
                    {{ message }}
            </p>
        {% endfor %}
{% endif %}

You could make a partial for messages, which I do sometimes. You can also use different message levels other than success.

Read more about them here: https://docs.djangoproject.com/en/3.1/ref/contrib/messages/

One way to approach this could be to use the success message.

from django.contrib import messages

def my_view(request):
   ...
   if form.is_valid():
      ....
      messages.success(request, 'Success message.')

To show one-time messages you can use Django's messages framework. Here is a custom login view that adds a "You are logged in" message:

from django.contrib.auth.views import LoginView
from django.contrib import messages

def MyCustomLoginView(LoginView):
    def form_valid(self, form):
        messages.add_message(self.request, messages.SUCCESS, 'You are logged in.')
        return super().form_valid(form)

And here is a template that will display this message:

{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}
Related