【问题标题】:if and elif doesn't work in template djangoif 和 elif 在模板 django 中不起作用
【发布时间】:2018-02-26 02:05:52
【问题描述】:

if 和 elif 在我的模板 django 中不起作用

index.html

<a style="{% if show.Ages == 19 %}background:#ff3636;{% elif show.Ages == 17 %}background:#fb9c92;{% elif show.Ages == 13 %}background:#ffb466;{% else %}background:#4aff68;{% endif %};border-radius: 15px;width: 140px;height: 42;margin-right: 831px;margin-top: -200;" class="button">رده‌ سنی‌:+{{ show.Ages }}</a>

views.py

def index(request):
    shows = show.objects.all()
    context = {
        'shows':shows
    }
    return render(request,'index.html', context)

models.py

class show(models.Model):
    Ages = models.CharField(max_length=10,default='',null=True)

有什么问题?

【问题讨论】:

  • 你为什么缺少冒号:
  • 这是shows 不是show
  • 这与您的问题无关,但请考虑将show 重命名为Show 并将Ages 重命名为ages。当 Python 开发人员看到一个大写字母时,他们认为是“类”,而不是“属性”。 official style guide 包含其他建议。
  • {% if show.Ages == 19 %} to {% if show.Ages == "19" %} 谢谢

标签: python html css django django-templates


【解决方案1】:

您的show.Ages 属性是CharField,而不是IntegerField。与其将其与整数进行比较,不如将其与字符串进行比较,例如

{% if show.Ages == '17' %}...{% endif %}

正如 cmets 中指出的,您的上下文变量是 shows,而不是 show,但我怀疑您的模板 sn-p 已经存在于类似的东西中

{% for show in shows %}...{% endfor %}

这将创建一个show 循环变量。

【讨论】:

    猜你喜欢
    • 2020-07-12
    • 2016-09-18
    • 2022-11-03
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多