【问题标题】:Django 'could not parse remainder' on related model call in templateDjango在模板中的相关模型调用上“无法解析余数”
【发布时间】:2018-12-10 00:06:43
【问题描述】:

当我尝试在我的模板

中调用它时
{% if member.departments.relationship(department).is_manager is True %}

我收到了这个错误

Could not parse the remainder: '(department).is_manager' from 'member.departments.relationship(department).is_manager'

但是当我调试我的视图时,同样的调用会起作用

(Pdb) member.departments.relationship(department).is_manager
True

这是我的看法

def department_detail(request, uid):
  department = Department.nodes.get(uid=uid)
  return render(request, 'department/detail.html', {'department': department,}) 

【问题讨论】:

  • 好吧,Django 模板语言故意不使用 Python 语言,而是一种有限的迷你语言,以防止人们(如您)在模板中编写业务逻辑。
  • @WillemVanOnsem 它看起来比实际复杂,如果有人是经理,我只是想在名称旁边添加一个图标。
  • 可以分享模型吗?我想你可能可以重写这里的逻辑。
  • @WillemVanOnsem 抱歉,不,我不能 =(它们不是标准 ORM。我正在研究自定义模板标签
  • member 在哪里被传递到模板中?

标签: django django-templates django-views django-template-filters templatetags


【解决方案1】:

为了解决这个问题,我使用了模板标签。有趣且强大的学习:

  • 将 /templatetags 添加到与 models.py 相同的目录中
  • 添加了 /templatetags/init.py
  • 添加了 /templatetags/department_extras.py

department_extras.py:

from django import template
from django.utils.safestring import mark_safe


register = template.Library()

@register.filter
def check_is_manager(member, department):
  if member.departments.relationship(department).is_manager is True:
    html_response = """<i class="fa fa-user-tie" title="Manager"></i>"""
  else:
    html_response = ""
  return mark_safe(html_response)

然后在模板中:

{% load department_extras %}
{{member|check_is_manager:department}}

免责声明:如果我使用的是标准的 ORM,那么我不会有这个问题,我只是将它用于视觉效果,而不是业务逻辑。如果不是因为 3 个视图和其他模型需要相同的功能,那么我会向模板传递一个额外的参数。

我喜欢模板标签,因为它们几乎就像子视图一样,可以作为跨视图的公分母,这样您就不必在每个视图的参数中不断传递补充数据。

【讨论】:

    猜你喜欢
    • 2016-06-13
    • 2015-12-23
    • 2015-05-05
    • 2019-04-20
    • 2023-03-21
    • 2019-07-24
    • 2020-11-26
    • 2013-03-17
    • 2018-12-18
    相关资源
    最近更新 更多