【问题标题】:Using ifequal in Django在 Django 中使用 ifequal
【发布时间】:2012-07-28 20:07:08
【问题描述】:

我确定我在这里遗漏了一些愚蠢的东西,但我正在尝试使用 ifequal 来评估模板变量。

这是我的模型:

USER_TYPES = (
('instructor', 'Instructor'),
('student', 'Student'),
)


class UserProfile(models.Model):
    type = models.CharField(
        choices=USER_TYPES, max_length=12
    )
    user = models.ForeignKey(
        User, 
        unique=True
    )

    def __unicode__(self):
        return u'%s' % (self.type)

...我在模板中使用它:

{% ifequal user.userprofile_set.get student %}
You're a student! 
{% endifequal %}

当我简单地打印出 {{ user.userprofile_set.get }} 我得到:

student

不知道我错过了什么 - 任何帮助表示赞赏!

【问题讨论】:

  • ifequal 在最近的 django 版本中已被弃用,只需使用 if a == b。将" 放在student 周围,并确保首先在django shell 上尝试:user.userprofile_set.get() == 'student'
  • 感谢您的评论 - 我最终使用了 {% if user.userprofile_set.get.type == "student" %},效果很好!

标签: django django-templates


【解决方案1】:

ifequal 已被弃用...但我认为这可行:

{% ifequal user.userprofile_set.get.type "student" %}
    Your a student! 
{% endifequal %}

【讨论】:

  • 只是想发布相同的内容。如果你只使用student Django 会“认为”它是一个模板变量。由于您与字符串进行比较,这当然行不通。
  • 感谢 cmets - 我最终使用了{% if user.userprofile_set.get.type == "student" %},效果很好!谢谢!
猜你喜欢
  • 2010-11-07
  • 2014-02-03
  • 2011-01-07
  • 2017-12-29
  • 2010-10-01
  • 2012-02-23
  • 2011-11-22
  • 1970-01-01
  • 2013-11-29
相关资源
最近更新 更多