Laurynas Tamulevičius
Laurynas Tamulevičius

Reputation: 1589

How to integrate Django authentication with Jinja2 templates properly?

I am trying to use authentication and authorisation system provided by Django and as I can see the default built-in views for login/logout expect Django templates, hence I cannot use my Jinja2 base.html file to extend them as I have already integrated Jinja2 engine.

I was able to solve this problem by replicating 'base.html' and changing syntax to Django template, but this approach forces me to rely on two same files in different templating languages.

However, now I have other issue, I cannot access the user object in Jinja2 template context, even though I can do that in Django template.

By saying 'I cannot access':

File "/home/dir/workspace/project/venv/local/lib/python2.7/site-packages/jinja2/environment.py", line 430, in getattr return getattr(obj, attribute)
UndefinedError: 'user' is undefined 

My Jinja2 template:

{% if user.is_authenticated %}
  <li>User: {{ user.get_username }}</li>
  <li><a href="{% url 'logout'%}?next={{request.path}}">Logout</a></li>
{% else %}
  <li><a href="{% url 'login'%}?next={{request.path}}">Login</a></li>
{% endif %}

My question is, how can I go around this problem? Should I just switch back Django templates, because this becomes more and more messy.

Upvotes: 2

Views: 3439

Answers (2)

Alasdair's answer is the best! So consider this an addendum: if you're converting a lot of DTL templates to Jinja2, and they all extend from a common base, consider putting in the base file something like:

{% if user is not defined %}
     {% set user=request.user %}
{% endif %}

Then you'll be able to use your prior user variables without a problem.

Upvotes: 2

Alasdair
Alasdair

Reputation: 309129

When you use the Django template language, you can use {{ user }} because the auth context processor is enabled. However using context processors with Jinja2 is discouraged.

You have access to request in the Jinja2 template context, so you can access request.user.

Supported in Django 1.10 and 1.11, required in Django 2.0+
{% if request.user.is_authenticated %}

Note that in Django < 1.10, user.is_authenticated() is a method so you must call it in the Jinja2 template:

Required in Django < 1.10, supported in Django 1.10 and 1.11
{% if request.user.is_authenticated() %}

Upvotes: 6

Related Questions