Non-destructive processing of user messages by Django

I display user messages through templates using RequestContext in Django, which provides access to user messages using the {{messages}} template variable - this is convenient.

I would like a user deleted messages - is there a way to do this in Django without rewriting a lot of code? Unfortunately, Django automatically deletes messages for each request - not very useful in this case.

Django doc says:

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

It would be ideal if you could just turn off automatic message deletion!


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

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

create myapp / context_processors.py file

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

enter 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
source share
1 answer

I know it sounds weird, but you can copy to your own list

request.user.message_set.all()

before creating the RequestContext, and then return them back.

+3
source

Source: https://habr.com/ru/post/1711947/


All Articles