tags:

views:

192

answers:

1

I'm displaying user messages through templates using RequestContext in Django, which gives access to user messages through {{messages}} template variable - that's convenient.

I'd like user him/herself delete the messages - is there a way to do it in Django without rewriting much code? Unfortunately Django automatically deletes messages at each request - not very useful in this case.

Django doc says:

"Note that RequestContext calls get_and_delete_messages() behind the scenes"

Would be perfect if there were a way to simply turn off the automatic deletion of messages!


NOTE: Unfortunately solution below makes admin interface unusable. I don't know how to get around this, really annoying.

EDIT - found a solution - use custom auth context processor that calls user.message_set.all() as Alex Martelli suggested. There's no need to change the application code at all with this solution. (context processor is a component in django that injects variables into templates.)

create file myapp/context_processors.py

and replace in settings.py in TEMPLATE_CONTEXT_PROCESSORS tuple django.core.context_processors.auth with myapp.context_processors.auth_processor

put into myapp/context_processors.py:

def auth_processor(request):
    """
    this function is mostly copy-pasted from django.core.context_processors.auth
    it does everything the same way except keeps the messages
    """
    messages = None
    if hasattr(request, 'user'):
        user = request.user
        if user.is_authenticated():
            messages = user.message_set.all()
    else:
        from django.contrib.auth.models import AnonymousUser
        user = AnonymousUser()
    from django.core.context_processors import PermWrapper
    return {
        'user': user,
        'messages': messages,
        'perms': PermWrapper(user),
    }
+3  A: 

I know it sounds like a strange approach, but you could copy into your own list

request.user.message_set.all()

before instantiating RequestContext, and later put them back in..

Alex Martelli
Alex, thanks. I think I found a good solution - posted it as update in my question.
Evgeny
Ah yes, excellent "packaging" of this idea, thanks @Evgeny.
Alex Martelli