Django messages framework with built-in Jinja2 backend - django

How can I use the Django messages framework with Jinja2 and the built-in Jinja2 backend in Django 1.8?
I tried doing it as before, but then remembered that the Jinja2 backend doesn't have the context processors of Django Templating Language. Is it possible via the request as with session.
I have been using Django only for a few months, so even if the answer is obvious, please let me know.

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

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).

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.

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.

Related

Django & Jinja2 templates using {{ url() }}

I am trying to figure out how to pass my user_id within my html using jinja's {{ url() }}, using urls that don't need any id like /dashboard/ work fine but I need to pass an id to this- example: /user/3 . I have tried the following with no success:
{{ url('detail') }}
{{ url('detail', user_id=User.id) }}
{{ url('detail', User.id) }}
Here's part of my views and html:
views.py
urlpatterns = [
path('dashboard/', dashboard, name='dashboard'),
path('user/<int:user_id>/', detail, name='detail'),
]
dashboard.html
{% for User in all_users %}
{{ url('detail') }}
{% endfor %}
Any help on this would be appreciated, thanks
I found a solution:
{% for User in all_users %}
{{ url('detail', args=[User.id] )}}
{% endfor %}
This also works:
{% url 'detail' user.id %}
Then, in views.py, your corresponding function should receive user_id as an argument (internally user.id becomes user_id).
Django now has official backend support for Jinja2 - I'm guessing you were using django-jinja which provides an implementation of the url function but it's fairly straightforward to integrate Django and Jinja now without adding any additional dependencies (besides Jinja2).
First, configure your TEMPLATES in your settings file and add a dictionary entry with the jinja2 backend:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'APP_DIRS': True,
'OPTIONS': {
'extensions': [<custom extensions if any>]
'environment': 'yourapp.jinja2.environment',
...
},
},
...
]
The key part of this is the environment setting. The examples suggest creating a jinja2.py file in your app directory and defining an environment function there that you'll set to a function that returns a Jinja2 Environment, e.g.,
# example yourapp/jinja2.py
from django.conf import settings
from django.urls import reverse
from django.templatetags.static import static
from jinja2 import Environment
def environment(**options):
env = Environment(**options)
env.globals.update({
'static': static,
'url': reverse,
'settings': settings,
...
})
return env
Here we are binding Python functions (and Django things) to be made available in our Jinja2 environment, so now static in a jinja template can be called static(...) and invoke the Django static function defined in django.templatetags.static, and url is bound to the Django reverse function so url('detail', args=[user.id]) should work. If you prefer a signature like {{ url('detail', pk=123) }} without generating an invalid arguments error you can define your own function:
def jinja_url(viewname, *args, **kwargs):
return reverse(viewname, args=args, kwargs=kwargs)
and bind 'url': jinja_url in your TEMPLATES settings instead.
It's also important to note that Django looks for your jinja templates in a jinja2 directory under your app dir, not the templates directory.

django crispy forms with jinja2

I want to use Jinja2 and Django crispy forms together, but when I load crispy_forms_tags in my template and trying to render form with this template tag, I get an error:
Encountered unknown tag 'crispy'. Jinja was looking for the following tags: 'endblock'. The innermost block that needs to be closed is 'block'.
My template code:
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="panel-heading"><h3>Registration</h3></div>
{% crispy form %}
{% endblock %}
How can I use this apps together?
Better solution:
templatetags.py
from crispy_forms.utils import render_crispy_form
from django_jinja import library
from jinja2 import contextfunction
#contextfunction
#library.global_function
def crispy(context, form):
return render_crispy_form(form, context=context)
In template:
{{ crispy(form) }}
Well, Geoffrey R.'s answer is a good approach, but the wrong method of jinja2 is used. Instead of render_crispy_form, it should be as_crispy_form. So, from crispy_forms.templatetags.crispy_forms_filters import as_crispy_form should be written at the beginning.
The corrected example jinja2.py file is as follows.
from crispy_forms.templatetags.crispy_forms_filters import as_crispy_form # this line is different
from django.contrib import messages
from django.contrib.staticfiles.storage import staticfiles_storage
from django.urls import reverse
from django.utils import translation
from jinja2 import Environment
def environment(**options):
env = Environment(
extensions=["jinja2.ext.i18n", "jinja2.ext.with_"], **options
)
env.globals.update(
{
"get_messages": messages.get_messages,
"static": staticfiles_storage.url,
"crispy": as_crispy_form, # this line is different
"url": reverse,
}
)
env.install_gettext_translations(translation)
return env
Other steps are same with Geoffrey R.'s answer.
It works for me, with the following pip packages:
Django==3.1.2
django-crispy-forms==1.9.2
Jinja2==2.11.2
By the way, I'm not using the django-jinja pip package.
Thanks Geoffrey R. for his great idea.
I found an easy, but not completed way to "hack in".
use 'django-jinja' package to register new filters;
in the filter file, define a crispy filter, which looks like:
from crispy_forms.templatetags.crispy_forms_filters import as_crispy_form
def crispy(form):
return as_crispy_form(form, 'Bootstrap3', form.helper.label_class, form.helper.field_class)
In the form Jinja template, I have to write more code than direct crispy tag in django template:
<form id='id_form' class="form-horizontal" method='post'>
{% csrf_token %}
{{form.media}}
{{ form|crispy() }}
<div>
<input type="submit" name="submit" value="Submit" class="btn btn-primary" id="submit-id-submit">
</div>
</form>
If anyone finds a more effective way to crispy forms, please let me know.
I have been struggling with this issue of yours and the given answer, although they might be relevant a few years ago, did not satisfy me.
So I went myself building a hack to make crispy forms work with Django 3.0.2 (I did not test the others versions, please let me know guys if there is any issue on any other version).
Install the relevant packages to make crispy forms work with Jinja2 :
pip install django-crispy-forms django-jinja
In your project directory (and NOT your application directory), make sure you have a jinja2.py file with:
from crispy_forms.utils import render_crispy_form
from django.contrib import messages
from django.contrib.staticfiles.storage import staticfiles_storage
from django.urls import reverse
from django.utils import translation
from jinja2 import Environment
def environment(**options):
env = Environment(
extensions=["jinja2.ext.i18n", "jinja2.ext.with_"], **options
)
env.globals.update(
{
"get_messages": messages.get_messages,
"static": staticfiles_storage.url,
"crispy": render_crispy_form, # THIS LINE IS RELEVANT
"url": reverse,
}
)
env.install_gettext_translations(translation)
return env
Make sure that your jinja2 template engine loads this option in your django's settings:
TEMPLATES = [
{
"BACKEND": "django.template.backends.jinja2.Jinja2",
"DIRS": [os.path.join(BASE_DIR, "jinja2")],
"APP_DIRS": True,
"OPTIONS": {"environment": "your_django_project.jinja2.environment"},
},
# ...
Note the "crispy": render_crispy_form, which will help you use crispy forms in your jinja2 templates.
Then, in your template, you can use:
{{ crispy(form) }}

Adapt a view if an app is installed with Django

I have a web app with a project that works alone (it's index, login.. pages).
I would need to change the index page if a new app is installed (e.g: add a link, a table in the template with my app models..). Have it dynamic.
The removal of the app must let the project intact and just remove the link.
How can I do that? Is it possible?
You can use the Django's application registry:
In [1]: from django.apps import apps
In [2]: apps.is_installed("django.contrib.admin")
Out[2]: True
An application can actually be enabled by using a dotted Python path to either its package or the application's configuration class (preferred). Simply checking if "app_name" is in settings.INSTALLED_APPS will fail in the latter case.
def my_view(request):
from django.conf import settings
app_installed = 'app_name' in settings.INSTALLED_APPS
return render_to_response(template_name, {'app_installed': app_installed})
template:
{% if app_installed %}
...
{% endif %}
Or use a custom context processor.
In installed_apps.py
from django.conf import settings
def installed_apps(request):
return {
'app_installed' : 'app_name' in settings.INSTALLED_APPS
}
In settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
...
'installed_apps.installed_apps'
)
simple_tag version:
The tricky part is that you can't pass arguments to your simple_tag when it's used in a conditional. Therefor, you create a new variable specifically for your installed app with as is_myapp_installed.
In templatetags/my_filters.py:
from django import template
register = template.Library()
#register.simple_tag
def is_app_installed(app):
from django.apps import apps
return apps.is_installed(app)
In template:
{% load my_filters %}
...
{% is_app_installed "myapp" as is_myapp_installed %}
{% if is_myapp_installed %}
...
{% endif %}

Django: How to get language code in template?

Is there's some global variable for gettin' language code in django template or atleast passing it through view?
something like: {{ LANG }} should produce "en" for example..
I really not comfortable when people using request.LANGUAGE_CODE.
Detailed explanation would be appreciated =)
It's an old topic. But some might find it useful.
{% load i18n %}
...
{% get_current_language as LANGUAGE_CODE %}
Django reference and example.
If it didn't already exist, you would need to write a template context processor. Here's how you'd do that.
Put this somewhere:
def lang_context_processor(request):
return {'LANG': request.LANGUAGE_CODE}
And then, add a reference to it the TEMPLATE_CONTEXT_PROCESSORS setting. Something like this:
from django.conf import global_settings
TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
'myproject.myapp.templatecontext.lang_context_processor',
)
(I recommend adding to the global setting because it means you don't break things accidentally when a new context processor is added to the defaults.)
However, it does exist, as the inbuilt template context processor django.template.context_processors.i18n. You can access it as LANGUAGE_CODE.
Purely for interest, here's the definition of that function:
def i18n(request):
from django.utils import translation
return {
'LANGUAGES': settings.LANGUAGES,
'LANGUAGE_CODE': translation.get_language(),
'LANGUAGE_BIDI': translation.get_language_bidi(),
}
Make sure that you're using a RequestContext for your template rendering, not a plain Context, or it won't work.
Tested with Django==1.11.2.
Enable I18N and employ i18n template context processor.
# setings.py
USE_I18N = True
# ...
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
# ...
'django.template.context_processors.i18n',
# ...
],
},
},
]
And then it's simple in the template.
# template.html
{% load i18n %}
{{ LANGUAGE_CODE }}
But use render(), not render_to_response(), in your view function so the LANGUAGE_CODE variable is accessible in the template:
render_to_response()
This function preceded the introduction of render() and works
similarly except that it doesn’t make the request available in the
response. It’s not recommended and is likely to be deprecated in the
future.

Django: sorl-thumbnail and easy-thumbnail in same project

I'm working on and project that uses two separate modular Django apps. However, one app requires easy-thumbnails and the other requires sorl-thumbnails. Unfortunately, the two thumbnail libraries make use of the template tag syntax {% load thumbnail %}, so they clash and break when a template using them tries to render.
Are there any approaches to solve this type of clash? (For example, a template option does to the effect of {% load thumbnail as easy_thumbnail %}). Am I going to have to fork one of the apps and replace one of the thumbnail libraries with another? If so, which should I choose to go with?
Thank you for considering my question,
Joe
In Django 1.9, you can use the libraries option of DjangoTemplates to include a tag library under a specified name. In the example below, the thumbnail library from sorl.thumbnail is included under the name sorl_thumbnail.
Note: the templatetag itself is not changed within the template... ie. remains thumbnail
Usage:
settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "foo", "templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
'libraries': {
'sorl_thumbnail': 'sorl.thumbnail.templatetags.thumbnail',
},
},
},
]
your_template.html
{% load sorl_thumbnail %}
{% thumbnail mymodel.image "640x480" crop="center" as im %}
<img src="{{ im.url }}" width="{{im.width}}" height="{{im.height}}"/>
{% endthumbnail %}
Sure, just write your own stub easy_thumbnail wrapper...
Create a thumbnailtags package in one of your django apps...
...making sure it's got an empty __init__.py
In thumbnailtags/easy_thumbnail.py do something like:
from django.template import Library
from easy_thumbnails.templatetags import thumbnail
register = Library()
def easy_thumbnail(parser, token):
return thumbnail(parser, token)
register.tag(easy_thumbnail)
Use {% load easy_thumbnail %}
Note:
You might also be able to do 'import thumbnail as easy_thumbnail, and skip the def easy_thumbnail bit, tho I've not tried that.
This blog link shows how to handle this.
https://timmyomahony.com/blog/using-sorl-thumbnail-and-easy-thumbnails-same-template/
(previously
http://timmyomahony.com/blog/2012/10/22/using-sorl-thumbnail-and-easy-thumbnails-same-template/)
UPDATE 2015
I had to do the following modifications to Tom Christie's answer in order to get this to work:
create a templatetags package in one of you local apps. It is important to name it templatetags. See django docs for template tags.
... make sure it has an __init__.py, empty or not.
In templatetags/easy_thumbnail.py do this:
from django.template import Library
from easy_thumbnails.templatetags import thumbnail
register = Library()
def easy_thumbnail(parser, token):
return thumbnail.thumbnail(parser, token) # the important bit
register.tag(easy_thumbnail)
Use {% load easy_thumbnail %} or - load easy_thumbnail with pyjade