Alternative to using message_set (especially for AnonymousUser)
On my Django site, I plan to use message_set in conjunction with some fancy user interface to alert the user to things like "your operation has completed successfully" or "you have three new messages".
The problem comes when I try to warn the user who is trying to log in that the user / password he provided is incorrect - AnonymousUser does not have a MessageSet for obvious reasons.
My question is, is my use of message_set good practice (or at least not crazy)? Any ideas on how I can workaround for the specific case of incorrect credentials? Should I take a look at a more complex solution (which I have no idea if it exists at all)?
Or you can use one of the following apps that provide solutions for more complex situations (e.g. multiple message types - notification - error - warrning, etc.).
django-flash - http://djangoflash.destaquenet.com/
django-notify - http://code.google.com/p/django-notify/
some discussion on the topic of custom messaging / notifications is posted on this blog post .
Just use a session to store the message and pull it out again in the 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 opinion:
# if login fails:
create_message(request, "Sorry, please try again")
In your template:
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
Not only is this approach better in that you can use it with anonymous users, but there is no database call like with the message_set method.