Dr Confuse
Dr Confuse

Reputation: 625

Django messages framework not displaying message?

I'm trying to build a community portal and am working on displaying one-time message to the user such as "login successful" and the like; and am working with Django's messages framework.

My template has the following line which currently does nothing:

{% if messages %}{% for message in messages %}<script>alert({{ message }});</script>{% endfor %}{% endif %}

Strangely, each of the following works:

{% if messages %}{% for message in messages %}<script>alert();</script>{% endfor %}{% endif %}

{% if messages %}{% for message in messages %}<script>alert("Welcome");</script>{% endfor %}{% endif %}

From this, I am concluding that I'm not creating, storing, or passing the messages correctly. However, I'm checking the docs and my syntax seems fine.

My message creation; views.py:

def login(request):

    userName = request.POST.get('usrname',None)
    userPass = request.POST.get('psw',None)

    user = authenticate(username=sanitize_html(userName), password=userPass)

    if user is not None:
        if user.is_active:
            auth.login(request, user)
        messages.add_message(request, messages.INFO, 'Successfully logged in!')
    else:
        messages.add_message(request, messages.INFO, 'Login not successful. Please try again.')

    return HttpResponseRedirect('/home/')

My message retrieval and passing, views.py (maps to url '/home/'):

def test(request):

    messagealert = []
    mess = get_messages(request)

    for message in mess:
        messagealert.append(message)

    if request.user.is_authenticated():
            student_user = get_student_user(request.user)
            student_user.first_name = request.user.first_name
            student_user.last_name = request.user.last_name
            student_user.email = request.user.email

            content = {
                'student_user': student_user,
                'messages': messagealert,
            }
    else:
            content = {
                'student_user': None,
                'messages': messagealert,
            }

    return render_to_response('index3.html', content)

My index3.html template is the template with the line given above.

What am I missing here?

Upvotes: 0

Views: 722

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599480

Don't use render_to_response in your test view. It doesn't run context processors which are required to insert things like messages - and other useful items such as user - into the context.

Use render instead:

return render(request, 'index3.html', context)

Upvotes: 1

Related Questions