2015-12-21 64 views
0

我是django的新手。在這裏,我嘗試使用django來做投票應用程序。 我想顯示 '您輸入正確'如果html裏面的條件

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> 
+0

如果在HTML文件中的條件沒有正常工作下。 – sunnysm

+0

如果html內部條件更好,稱爲模板:) – aliasm2k

+0

爲什麼你將'if'語句分成兩個語句?是否{{%if selected_choice =='Yellow'%}'解決了問題? – soon

回答

1

如果selected_choice是一個字符串值:

'=='前後的空格是impo rtant;這通常是錯過的。

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

你也可以嘗試:

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

我做了這樣的事,但沒有得到答案 – sunnysm

+0

什麼是'selected_choice'?它是一個對象嗎?我假設是因爲你調用了save()方法。您是否將存儲的值稱爲「黃色」作爲其領域之一?在這種情況下,您需要聲明像{%if selected_choice.name ==「Yellow」%}。 – rkatkam

+0

我知道了..我將類型(selected_choice)轉換爲string.that生成確切的答案 – sunnysm