Search code examples
pythonhtmldjangopython-3.xdjango-views

Why do my Django messages get duplicated?


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>

Solution

  • 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.