【问题标题】:Django tag on template模板上的 Django 标记
【发布时间】:2020-12-24 14:00:36
【问题描述】:

我的代码:

{% if request.user.is_staff %}
  {% extends "base.html" %}
    {% load crispy_forms_tags %}
    {% block content %}
      <div class="content-section">
          <form method="POST">
              {% csrf_token %}
              <fieldset class="form-group">
                  <legend class="border-bottom mb-4">
                      Create A Post
                  </legend>
                  {{ form|crispy }}
              </fieldset>
              <div class="form-group">
                  <button class="btn btn-outline-info" type="submit">
                      Post
                  </button>
              </div>
          </form>
      </div>
    {% endblock content %}
{% else %}
  <head>
    <meta http-equiv="refresh" content="5; url=/" />
  </head>
  <body>
    <h1>Restricted Access To Staff!</h1>
    <p>You will be redirected to the home page in 5 seconds</p>
  </body>
{% endif %}

错误:

我不知道为什么它不起作用,这可能与 {% if request.user.is_staff %} 位有关吗?

【问题讨论】:

  • {% extends %} 应该始终是 first 模板标签,因此不允许在 {% if %} ... {% else %} 子句中移动。

标签: python django django-views django-templates django-tagging


【解决方案1】:

作为documentation on template inheritance says

如果您在模板中使用{% extends %},它必须是该模板中的第一个模板标签。否则模板继承将不起作用。

因此您无法使用{% if … %} … {% else %} … {% endif %} template tag [Django-doc] 来确定是否继承。

你可以把这个逻辑移到视图中,所以:

def some_view(request):
    # …
    if request.user.is_staff:
        return render(request, 'my_template.html', context)
    else:
        return render(request, 'my_other_template.html', context)

开发一个装饰器可能会更好,它会自动检查用户是否是员工,并正确呈现内容,例如:

from functools import wraps

def requires_staff_redirect(f):
    @wraps(f)
    def g(request, *args, **kwargs):
        if not request.user.is_staff:
            return render(request, 'my_other_template.html')
        else:
            return f(*args, **kwargs)
    return g

然后我们可以像这样装饰一个视图:

@requires_staff_redirect
def my_view(request):
    # …

只有当用户是员工时才会触发视图,否则会渲染my_other_template.html页面。

【讨论】:

  • 如何使用类模板来做到这一点?
猜你喜欢
  • 2020-10-29
  • 2012-11-29
  • 2020-09-27
  • 1970-01-01
  • 2014-08-07
  • 1970-01-01
  • 2019-10-07
  • 2017-03-09
  • 2018-10-21
相关资源
最近更新 更多