views:

122

answers:

2

In my Django site, I am planning on using message_set combined with some fancy UI to warn the user of things like "your operation was completed successfully" or "you have three new messages".
The problem arises when I try to warn an user that is trying to log in that the user/pass he provided are wrong - AnonymousUser, for obvious reasons, does not have a MessageSet.

My question: is my use of message_set good practice (or at least not insane)? Any ideas on how I could workaround for the specific case of wrong login credentials? Should I look to some more complex solution (which I have no idea if it even exists)?

+3  A: 

Just use the session to store the message, and pull it out again in a template tag or context processor:

def create_message(request, message):
    messages = request.session.get('messages', [])
    messages.append(message)
    request.session['messages'] = messages

def get_messages(request):
    messages = request.session.pop('messages', [])
    return {'messages' : messages}

In your view:

# if login fails:
create_message(request, "Sorry, please try again")

In your template:

{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}

This approach is not only better in that you can use it with anonymous users, but there is no database call as with the message_set approach.

Beachy
+3  A: 

Or you can use one of the following application which provide solutions for more complex situations (e.g. multiple message types - notice - error - warrning etc.)

django-flash - http://djangoflash.destaquenet.com/

django-notify - http://code.google.com/p/django-notify/

some discussion on the user messaging/notification subject is placed on this blog post.

vinilios
Thanks. I like reusable code! :)
Agos