Question

I use django.contrib.messages module to create flush messages. These messages can be shown in different blocks on the page, depends on extra tag:

messages.error(request, 'Error message', extra_tags='form')

I have default tag named 'global' and I need to add it in new message if no extra_tags set. So I wrote middleware to wrap django.contrib.messages.add_message() method on application start:

class Initialization:
    def __init__(self):
        self.init_messages()
        raise MiddlewareNotUsed

    def init_messages(self):
        add_message_method = messages.add_message
        def add_message_wrapper(request, level, message, extra_tags='', fail_silently=False):
            if not extra_tags:
                extra_tags = 'global'
            add_message_method(request, level, message, extra_tags, fail_silently)
        messages.add_message = add_message_wrapper

I see that init_messages() method is called, but when I call django.contrib.messages.add_message(), it is not wrapped with add_message_wrapper().

Where is my fail?

Was it helpful?

Solution

Couldn't you just add the "startup code" into settings.py or in views.py instead?

If all you are doing is adding a default value "global" whenever extra_tags is empty, you could also do that within the page template while rendering your messages:

{% if not message_obj.tags %}
    // Use "global"
{% else %}
    // Use {{message_obj.tags}}
{% endif %}

This can also be done inside your view code:

storage = messages.get_messages(request)
for message in storage:
    if not message.tags:
        message.tags = "global"
storage.used = False

See the Django docs for more info https://docs.djangoproject.com/en/dev/ref/contrib/messages/#expiration-of-messages

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top