0

imageDjango displays twice the same message, even when the messages are not passed in the views.py.

#login.html
{% extends 'login_system/base.html' %}
{% block body %}
    {% for message in messages %}
        {% if message.tags == 'error' %}
            <div class="alert alert-danger" role="alert">
              {{ message }}
            </div>
        {% endif %}
    {% endfor %}
    <form method="POST">
        {% csrf_token %}
        {{ form }}
        <button type="submit" class="btn btn-primary">Submit</button>
    </form>
{% endblock %}
# views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import RegisterForm, LoginForm
# Create your views here.
def login(request):
    if request.method == 'POST':
        form = LoginForm(data=request.POST)
        print(request.POST)
        if form.is_valid():
            messages.success(request, 'Successfully Logged In!')
            print('ok')
            return redirect('home_page')
        else:
            #print(form.errors.get_json_data())
            if form.errors:
                for error in form.errors.get_json_data()['__all__']:
                    messages.error(request, error['message'])
            else:
                messages.error(request, 'Something went wrong. Please try again.')
            print('nie ok')
    else:
        form = LoginForm()
    return render(request, 'login_system/login.html', {'form': form})

This code renders error message twice for me. One is from the views.py, Second I do not know. The base.html file can look like this

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% block body %}
{% endblock %}
</body>[![enter image description here][1]][1]
</html>

And I can delete sending message from the views.py and the nonstyled version still is rendered. Why is that?

Aleksander Ikleiw
  • 2,549
  • 1
  • 8
  • 26
  • 1
    Because `{{ form }}` will render the error messages as well. There i thus no need to add these as messages. – Willem Van Onsem May 11 '21 at 19:21
  • @WillemVanOnsem thanks, how can I edit the style of messages from `form` or do not render them at all? – Aleksander Ikleiw May 11 '21 at 19:23
  • Does this answer your question? [Custom-formatted Django form errors appearing twice](https://stackoverflow.com/questions/53710769/custom-formatted-django-form-errors-appearing-twice) – lucutzu33 May 11 '21 at 19:37

0 Answers0