How to show the errors in the template?

Viewed 96

Working on a simple project using Django, and just finished the login/register form. What I'm trying to do is to show up the errors when the user doesn't do something in the right way(ex: not matching the password) I did the login/register form by using this library from django.contrib.auth import authenticate, login, logout and It did pretty well.

How can I show the errors in the template?

1 Answers

Import messages in your views.py

from django.contrib import messages

and use it like given below

def signUp(request):
    # Code here
    if (condition):
        messages.error(request, "message")

Here, the error is the message tag and the second argument of the messages.error function is the actual message.
Then in your html file run this for loop where you wanted to show the error

  {% for message in messages %}
  <div class="alert alert-{{message.tags}} alert-dismissible fade show" role="alert">
    <strong>Message: </strong> {{message}}
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
  </div>
  {% endfor %}

There are 5 message tags -

  • debug
  • info
  • warning
  • success
  • error
Related