【问题标题】:if condition inside htmlhtml中的if条件
【发布时间】:2015-12-21 09:02:03
【问题描述】:

我是django 的新手。在这里,我尝试使用 django 做一个投票应用程序。 我想显示'你输入正确'

if selected_choice='Yellow'

这是我的代码

def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
    # Redisplay the question voting form.
        return render(request, 'polls/detail.html', {
        'question': question,
        'error_message': "You didn't select a choice.",
    })
    else:

        selected_choice.votes += 1
        selected_choice.save()
        context_dict={}
        context_dict['selected_choice']=selected_choice
        context_dict['question']=question

        return render(request, 'polls/result.html', context_dict)

html文件

<h1>{{ question.question_text }}</h1>
{% if selected_choice  %}
    {% if 'Yellow' %}

    <p> you entered correct </p>
    {% endif %}

{% endif %}


<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{     choice.votes|pluralize }}</li>
{% endfor %}
</ul>

【问题讨论】:

  • 以下如果html文件中的条件不能正常工作。
  • 这个 if html 中的条件最好称为模板 :)
  • 您为什么将您的if 语句拆分为两个语句? {% if selected_choice == 'Yellow' %} 解决问题了吗?
  • @rkatkam 的正确答案如下 - 请参阅文档 - docs.djangoproject.com/en/1.6/ref/templates/builtins/#operator

标签: python html css if-statement


【解决方案1】:

如果 selected_choice 是字符串值:

'==' 前后的空格很重要;通常会错过。

   {% if selected_choice == 'Yellow' %}
    <p> you entered correct </p>
   {% endif %}

你也可以试试:

   {% ifequal selected_choice 'Yellow' %} 
    <p> you entered correct </p>
   {% endifequal %}

【讨论】:

  • 什么是'selected_choice'?它是一个对象吗?我假设是因为你调用了 save() 方法。您是否将值“黄色”存储为其字段之一?在这种情况下,您需要声明 {% if selected_choice.name == "Yellow" %}。
  • 我明白了..我将 type(selected_choice) 转换为 string.that 产生准确的答案
猜你喜欢
  • 1970-01-01
  • 2018-12-26
  • 2013-04-24
  • 2014-05-31
  • 2015-10-12
  • 2021-11-08
  • 2020-10-07
  • 1970-01-01
  • 2017-02-15
相关资源
最近更新 更多