0

I'm using django messages system to show a toast message. I tried to prevent users from accessing "logout" when they are not logged in, and show a warning toast. When I type in the url the first time, it didn't show up anything, but since the second time, it keeps showing 2 toast messages.

I tried using this solution but instead of removing my duplicate message, it doesn't show up anything more.

def logout_request(request):
    if not request.user.is_authenticated:
        messages.warning(request, "You must log in to log out!")
        return redirect("/")

    logout(request)
    messages.info(request, "Logged out successfully!")
    return redirect("/")
<div class="message-wrapper">
{% for msg in messages %}
    <div class="toast" data-autohide="true" data-delay="1500">
        {% if msg.tags == 'success'%}
        <div class="toast-header toast-header-success">
            <strong class="mr-auto">Success</strong>
        {% elif msg.tags == 'info'%}
        <div class="toast-header toast-header-primary">
            <strong class="mr-auto">Information</strong>
        {% elif msg.tags == 'warning'%}
        <div class="toast-header toast-header-warning">
            <strong class="mr-auto">Warning</strong>
        {% elif msg.tags == 'error'%}
        <div class="toast-header toast-header-danger">
            <strong class="mr-auto">Error</strong>
        {% endif %}
            <button type="button" class="ml-2 mb-1 close button-close" data-dismiss="toast" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <div class="toast-body">
            {{ msg }}
        </div>
    </div>
{% endfor %}
</div>
quanpham0805
  • 277
  • 2
  • 5
  • 14
  • In your template, at the top of the `for` loop, print `{{ msg.tags }}` to make sure it's what you're expecting. – John Gordon Jun 09 '19 at 01:26
  • I tried putting ```

    {{msg.tags}}

    ``` and the tags was ```warning```, which is what I expected. The problem is, instead of showing nothing in the first time I tried, it showed the tags and 1 toast message, and after the second time and so on, it showed 2 toasts
    – quanpham0805 Jun 09 '19 at 01:33
  • **Django** messages are based on ```Cookies```. It means, that if you should delete cookies. You should ```iterate``` over messages in your templates, every time. Otherwise, it will be duplicated ! – gachdavit Jun 09 '19 at 05:16
  • I've already used ```{% for msg in messages %}```, but I don't know why it just skipped my fist message. – quanpham0805 Jun 10 '19 at 02:25

1 Answers1

0

I still don't know why, but when I change my laptop, it just work exactly what I expect. It seems to me that my previous laptop has some trouble with cache or something. I deleted cache data and open the dev tools, it just works magically.

quanpham0805
  • 277
  • 2
  • 5
  • 14