if condition inside html

39,158

If selected_choice is a string value:

The white-space before and after '==' is important; which is usually missed.

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

You may also try:

   {% ifequal selected_choice 'Yellow' %} 
    <p> you entered correct </p>
   {% endifequal %}
Share:
39,158
sunnysm
Author by

sunnysm

Updated on July 09, 2022

Comments

  • sunnysm
    sunnysm almost 2 years

    I am new in django. Here I'm try to do a poll app using django . I want to display 'you entered correct'

    if selected_choice='Yellow'
    

    Here is my code

    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 file

    <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>
    
    • sunnysm
      sunnysm over 8 years
      the following if condition in html file did not work properly.
    • aliasm2k
      aliasm2k over 8 years
      This if condition inside html is better called templates :)
    • awesoon
      awesoon over 8 years
      Why did you split your if statement into two statements? Does {% if selected_choice == 'Yellow' %} solve the problem?
    • Craicerjack
      Craicerjack over 8 years
      @rkatkam has the correct answer below - see the docs - docs.djangoproject.com/en/1.6/ref/templates/builtins/#operat‌​or
  • rkatkam
    rkatkam over 8 years
    what is 'selected_choice'? Is it an object? I assume so because you calling save() method on it. Are you storing the value say 'Yellow' as one of its field? In such case you need to state that like {% if selected_choice.name == "Yellow" %}.
  • sunnysm
    sunnysm over 8 years
    i got it..i convert the type(selected_choice) to string.that produce exact answer