【问题标题】:Tag If in template django在模板django中标记If
【发布时间】:2015-05-14 18:58:21
【问题描述】:

工作代码:

  {% if request.user.manager.position != 'E' %}
      {% endif %}

models.py

Position_choices = (('M', u'Manager'), ('E', u'Staff'), ('U', u'Other_staff'))
class Manager(models.Model):
...
    position = models.CharField(max_length=1, choices=Position_choices, default='M')

用于项目的models.py

class Project(models.Model):
    manager = models.ForeignKey(Manager, blank=True, null=True, related_name='manager_set')
    Other_staff = models.ForeignKey(Manager, blank=True, null=True, related_name='staff_set')
    Staff= models.ForeignKey(Manager, blank=True, null=True, related_name='otherstaff_set')

我在页面 html 上显示了一些块,具体取决于员工职位。但是以前只有一个员工,现在是2个。我试试:

 {% if request.user.manager.position in ['E', 'U'] %}

结果:

Could not parse the remainder: '['E',' from '['E','

请您帮忙正确查询。

【问题讨论】:

    标签: python django


    【解决方案1】:

    Django 模板不支持列表文字,我想说最简单的方法是将列表 ['E', 'U'] 作为变量传递,然后再做:

    {% if request.user.manager.position in allowed_positions %}
    

    【讨论】:

      【解决方案2】:

      上一个相关问题:Checking if something exists in items of list variable in Django template

      解决问题的方法有两种:

      1. 在 Python 后端创建选择列表并通过上下文进行比较:

      {% if request.user.manager.position in request.positive_list %}

      1. 用 OR 分割条件:
      {% if request.user.manager.position == 'E' | request.user.manager.position == 'U' %}
      

      【讨论】:

        【解决方案3】:

        尝试将具有有效位置的列表作为变量发送到模板。您不能直接在模板中“定义”列表。

        【讨论】:

          猜你喜欢
          • 2011-08-13
          • 1970-01-01
          • 2011-11-19
          • 2020-10-29
          • 1970-01-01
          • 1970-01-01
          • 2016-07-25
          • 2020-09-27
          • 1970-01-01
          相关资源
          最近更新 更多