【问题标题】:Where to import stuff for a template in Django?在哪里为 Django 中的模板导入东西?
【发布时间】:2018-06-16 13:25:14
【问题描述】:

抱歉这个愚蠢的问题,我迷路了。

我得到了一个模板和一个模板标签:

menu_tags.py

from django import template
from menu.models import Button

register = template.Library()

@register.inclusion_tag('menu/home.html')
def show_menu():
    buttons = Button.objects.all()
    return {'buttons': buttons}

还有这个:

home.html

    {% for button in buttons %}
    {% if user.is_authenticated %}
      stuff
    {% endif %}
    {% endfor %}

我想知道,我怎样才能让 user.is_authenticated 工作?我知道我必须导入一些东西,但是在哪里?在 menu_tags 中导入它似乎不起作用。

谢谢!

【问题讨论】:

  • 或者你可以使用request.user.is_authenticated
  • 总是为我返回 false。
  • 用户是否已通过身份验证?用什么方法?
  • 使用基本的 Django 系统...我可以在我的基本模板中使用“user.is_authenticated”,但如果这对您有帮助,则不能在我的菜单应用程序中使用...
  • request 在模板标签中不可用。你必须先得到它。在这里查看答案:Access request in django custom template tags。然后使用request.user.is_authenticatated。

标签: django


【解决方案1】:

根据 cmets 中其他用户的建议,尝试以下操作:

from django import template
from menu.models import Button

register = template.Library()

@register.inclusion_tag('menu/home.html', takes_context=True)
def show_menu():
    request = context['request']
    if request.user.is_authenticated: # if Django 1.10+
        buttons = Button.objects.all()
    else:
        buttons = None
    return {'buttons': buttons}

然后在您的模板中,确保您加载了新的模板标签并尝试:

{% load menu_tags %}

{% for button in buttons %}
  {{ button }}
{% endfor %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-20
    • 1970-01-01
    • 1970-01-01
    • 2015-08-18
    • 2017-03-19
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    相关资源
    最近更新 更多