How to get my messages to show on Django for a registration form?


I am creating a registration form using the Django framework and I want to display some error messages to the user if they enter the wrong confirm password, or an email already taken etc. I have written the code and it seems to be working, but I can’t seem to get the messages to show on screen upon redirecting to back to registration page if there is an error in the form. I have imported messages on the page (from django.contrib import messages) and I think my is all configured correct:

Here is my code:

def register(request):
if request.method == "GET":
    register_form = RegisterForm()
    return render(request, "main/register.html", {
        'form': register_form
    register_form = RegisterForm(request.POST)
    if register_form.is_valid():
        first_name = request.POST['first_name']
        last_name = request.POST['last_name']
        username = request.POST['username']
        email = request.POST['email']
        password = request.POST['password']
        confirm_password = request.POST['confirm_password']

        if password == confirm_password:
            if User.objects.filter(email=email).exists():
          , 'Email or user name Already taking')
                    return redirect('register')
            elif User.objects.filter(username=username).exists():
          , 'username is taken')
                    return redirect('register')
                first_name=first_name, last_name=last_name, email=email, 
                return redirect('main/login.html')
            messages.error(request, 'Password Not Match')
            return redirect('register')   
        #return redirect ('/')     
        return render(request, 'main/login.html')

and this is my register.html form:

          <form action="{% url 'register' %}" method="POST">
                {% csrf_token %}
                    <legend>Enter details</legend>
                        {{ form.as_table }}
                        <button type="submit" class="mybutton _f-purple" value="submit">Register</button>


I think this is what you need.

          {% if messages %}
            <div class="mgs-area">
                <div class="mgs-item">
                {% for message in messages %}
                <span {% if message.tags %} class="nav_item message-{{ message.tags }} " {% endif %}> {{ message }} </span>
                {% endfor %}
            {% endif %}

You can style success or error messages differently.

class="nav_item message-{{ message.tags }}

Answered By – sk1p

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published