[Django]-Django messages framework with built-in Jinja2 backend

3👍

In the end I decided to go with the Jinja2 environment. I added a global callable to the environment like ‘messages’: messages.get_messages, which will let me access it like a context processor, but with messages(request) instead of the object ‘messages’ in DTL.

For beginners like me who doesn’t know much about Jinja2, I added this callable to the jinja2.py file, which we create for enabling Jinja2 backend, just below the callable for url. You also have to import messages module from django.contrib in this file. Now, you can access the messages store from the Jinja2 template by accessing it using messages(request).

12👍

To expand a bit on the answer above, here’s the step-by-step breakdown.

First, enable a custom Environment for jinja2, as described here

In settings.py, point the environment option for jinja2 to some function

`TEMPLATES = [
        {
            "BACKEND": "django_jinja.backend.Jinja2",
            "APP_DIRS": True,
            "OPTIONS": {
                "match_extension": ".jinja",
                "environment": "myapp.jinjaconfig.environment",
            }
        },
...]`

Now you write that function to add messages to the environment. Create myapp/jinjaconfig.py (or whatever name you choose, to match what you added to settings.py):

from jinja2 import Environment
from django.contrib import messages

def environment(**options):
    env = Environment(**options)
    env.globals.update({
        'get_messages': messages.get_messages,
        })
    return env

At this point you have get_messages available in your template. You can use it like this:

{% for message in get_messages(request) %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}

Note that you have to pass in the request as an argument there

1👍

There’s a ticket 24694 about adding support for OPTIONS['context_processors'] to the Jinja2 template backend.

One of the suggestions from the discussion (it’s quite long!) is to use django-jinja.

0👍

Use the django_jinja package.

In your settings.py file, you will be able to add a context_processor like the example below and it works without doing anything else:

# Just an example
TEMPLATES = [
    {
        "BACKEND": "django_jinja.backend.Jinja2",
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.contrib.messages.context_processors.messages",
            ],
        }
    },

Doing this will merge the messages context into the template context.

Leave a comment