简体   繁体   English

如何将Django身份验证与Jinja2模板正确集成?

[英]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. 我正在尝试使用Django提供的身份验证和授权系统,并且可以看到默认的内置视图用于登录/注销期望Django模板,因此,由于我已经集成了Jinja2,因此无法使用Jinja2 base.html文件扩展它们发动机。

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. 我能够通过复制'base.html'并将语法更改为Django模板来解决此问题,但是这种方法迫使我依赖于不同模板语言的两个相同文件。

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. 但是,现在还有其他问题,即使我可以在Django模板中执行此操作,也无法在Jinja2模板context访问user对象。

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: 我的Jinja2模板:

{% 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. 我是否应该切换回Django模板,因为这变得越来越混乱。

When you use the Django template language, you can use {{ user }} because the auth context processor is enabled. 使用Django模板语言时,可以使用{{ user }}因为已启用auth上下文处理器。 However using context processors with Jinja2 is discouraged . 但是,不建议将上下文处理器与Jinja2一起使用

You have access to request in the Jinja2 template context, so you can access request.user . 您可以在Jinja2模板上下文中访问request ,因此可以访问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: 请注意,在Django <1.10中, user.is_authenticated()是一种方法,因此必须在Jinja2模板中调用它:

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

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: 因此,请考虑以下内容:如果要将许多DTL模板转换为Jinja2,并且它们都从通用基础扩展而来,请考虑在基础文件中添加以下内容:

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

Then you'll be able to use your prior user variables without a problem. 然后,您将可以使用先前的用户变量而不会出现问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM