Search code examples
djangodjango-templatesdjango-messages

Django Messages show up only in admin


I have set up a django message that gets displayed when the user logs in, but the messages show up only in the admin.

accounts/views.py


def login_page(request):
    form = LoginForm(request.POST or None)
    context = {
        'form':form
    }
    next_ = request.GET.get('next')
    next_post = request.POST.get('next')
    redirect_path = next_ or next_post or None
    if form.is_valid():
        username = form.cleaned_data.get("username")
        password = form.cleaned_data.get("password")
        user = authenticate(request, username=username,password=password)
        if user is not None:
            login(request, user)
            try:
                del request.session['guest_email_id']
            except:
                pass
            if is_safe_url(redirect_path,request.get_host()):
                return redirect(redirect_path)
            else:
                messages.info(request,"You are now logged in")
                return redirect("/")
        else:
            messages.error(request,"Something went wrong")
            print("Error")
    return render(request,"accounts/login.html", context)

settings.py

MESSAGE_STORAGE = 'django.contrib.messages.storage.fallback.FallbackStorage'

'OPTIONS': {
'context_processors': [             
    ...
    'django.contrib.messages.context_processors.messages',

base.html

{% if message is not None %} {% for message in messages %}{{ message }}{% endfor %}{% else %}{% endif %}


Solution

  • You should remove the {% if message is not None %} condition. Especially since at that point, message is not defined yet. You can check for messages. But then you should not check against None, but just check the truthiness, like:

    {% if messages %}
        {% for message in messages %}
            {{ message }}
        {% endfor %}
    {% endif %}

    If you however do not want to render something around these messages (like an <ul> … </ul>), you can simply omit the {% if %} … {% endif %}).

    For more information, see the documentation on displaying messages.