0

I've came across an issue where message is displayed twice even though its called only once. Sometimes only one message is displayed however, most of the time 2 messages are.

Messages showing like below:

My view:

def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, f'Account created has been creted! You can log-in now.')
            return redirect('login')
    else:
        if request.user.is_authenticated:
            messages.error(request, 'You are loged-in and in order to registrate you must be loged-out.')
            return redirect('blog-home')
        else:
            form = UserRegisterForm()
    return render(request, 'users/register.html', {'form': form,'title':'Register Page'})

And here is my template:

Base.html

{% load static %}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}">

    {% if title %}
        <title> Django blog - {{ title }}</title>
    {% else %}
        <title> Django blog</title>
    {% endif %}
</head>
<body>
<header class="site-header">
    <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top">
        <div class="container">
        <a class="navbar-brand mr-4" href="{% url 'blog-home' %}">Django Blog</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarToggle">
            <div class="navbar-nav mr-auto">
            <a class="nav-item nav-link" href="{% url 'blog-home' %}">Home</a>
            <a class="nav-item nav-link" href="{% url 'blog-about' %}">About</a>
            </div>
            <!-- Navbar Right Side --> 
            <div class="navbar-nav">
                {% if user.is_authenticated %}
                <a class="nav-item nav-link" href="{% url 'profile' %}">{{ user.username }}</a>
                <a class="nav-item nav-link" href="{% url 'logout' %}">Logout</a>
                {% else %}
                <a class="nav-item nav-link" href="{% url 'login' %}">Login</a>
                <a class="nav-item nav-link" href="{% url 'register' %}">Register</a>
                {% endif %}
            </div>
        </div>
        </div>
    </nav>
</header>

<main role="main" class="container">
    <div class="row">
    <div class="col-md-8">
        {% if messages %}
            {% for message in messages %}
                {% if message.tags == 'error' %}
                    <div class="alert alert-danger">
                        {{ message }}
                    </div>
                {% else %}
                    <div class="alert alert-{{ message.tags }}">
                        {{ message }}
                    </div>
                {% endif %}
            {% endfor %}
        {% endif %}
        {% block content %}{% endblock %}
    </div>
    <div class="col-md-4">
        <div class="content-section">
        <h3>Our Sidebar</h3>
        <p class='text-muted'>You can put any information here you'd like.
           <ul class="list-group">
            <li class="list-group-item list-group-item-light">Latest Posts</li>
            <li class="list-group-item list-group-item-light">Announcements</li>
            <li class="list-group-item list-group-item-light">Calendars</li>
            <li class="list-group-item list-group-item-light">etc</li>
            </ul>
        </p>
        </div>
    </div>
    </div>
</main>

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>

You can see that in the {% if messages %} block, message is called only once.

And here is the main html:

{% extends "blog/base.html" %}
{% block content%}
{% for post in posts %}
<article class="media content-section">
    <div class="media-body">
        <div class="article-metadata">
            <a class="mr-2" href="#">{{ post.author.first_name }}</a>
            <small class="text-muted">{{ post.date_posted|date:"d F, Y"}}</small>
        </div>
        <h2><a class="article-title" href="#">{{ post.title }}</a></h2>
        <p class="article-content">{{ post.content }}</p>
    </div>
</article>
{% endfor %}
{% endblock content%}

Any ideas what could be causing this?

Oliver.R
  • 1,282
  • 7
  • 17
Roitko
  • 117
  • 1
  • 8
  • You have a for loop which will print each message in messages. so chances are messages contains more than one message. How is messages populated/managed/cached/cleared? – Chris Doyle Mar 16 '20 at 11:25
  • refer this one -> https://stackoverflow.com/questions/5401118/django-messages-being-displayed-twice/9121754 – rahul.m Mar 16 '20 at 11:37
  • @ChrisDoyle its created in the register function in "My view" - messages.error. It is not cleared nor cached. Do you think it is needed? – Roitko Mar 16 '20 at 11:43
  • @c.grey I already checked this article but was not applicable for me as I dont have the same same block in 2 different templates. – Roitko Mar 16 '20 at 11:45
  • 2
    "Sometimes only one message is displayed however, most of the time 2 messages are" => you have to find out in which cases it works fine and in which cases you get the two messages. Messages are cleared when rendered, but if you end up going twice thru this branch of the view before anything is rendered, you indeed get the message twice. – bruno desthuilliers Mar 16 '20 at 11:58
  • @brunodesthuilliers I already tested that and after loging-in, accessing the registration page for the first time then no message shows. Then after accessing it again 2 messages shows. Then after accessing again only one message and then after accessing the page only 2 messages shows until I dont log out. – Roitko Mar 16 '20 at 12:05
  • 1
    "after loging-in, accessing the registration page for the first time then no message shows" => it should. Trace your code execution (with `print()` or logging or pdb), that's the best way to find out what happens. Also, make sure ALL your templates inherit from base.html. – bruno desthuilliers Mar 16 '20 at 12:13
  • @brunodesthuilliers as I am a beginner could you please tell me what would be the best thing to print out? I tried printing simple string and I can see it whenever I refresh the page. I put it between `massages.error` and `return` in my views. However, this did not help me much as I was still not able to find what was causing this. (FYI all my templates inherit only from base.html already) – Roitko Mar 16 '20 at 13:14
  • That's a good place to start. Now you want to try and reproduce the scenarii you have identified (cf your previous comment) while watching your devserver's output and check whether your debug traces match the observed behaviour. What puzzles me the most is actually the "after loging-in, accessing the registration page for the first time then no message shows"... – bruno desthuilliers Mar 16 '20 at 13:42
  • @brunodesthuilliers thank you for you help but did not manage to find anything. It works as expected and prints whenever I access the page so I do not understand why the message shows twice while the print shows only once. Ill leave it just like this for future and maybe once I am more knowledgeable of Django I will try to fix it! Thanks! – Roitko Mar 16 '20 at 16:57
  • Well, you could monkeypatch   `messages.error()` to trace calls and find out whether there's any other call with the same message elsewhere... – bruno desthuilliers Mar 17 '20 at 09:23

0 Answers0