[Django]-Django: Selectively Apply CSS Styles to Quiz Radio Buttons

2πŸ‘

βœ…

You can accmoplish this with some CSS and minimal templating.

Consider the following HTML template

The key here is class="answer{% if answer == solution %} solution{% endif %}"

<h2>{{ question }}</h2>
<form>
{% for answer in answers %}
    <label for="answer{{ forloop.counter }}">{{ answer }}</label>
    <input id="answer{{ forloop.counter }}" type="radio" name="answer" class="answer{% if answer == solution %} solution{% endif %}" value="{{ answer }}">
    <br/>
{% endfor %}

<p class="result incorrect">Sorry, that was not correct. The solution was {{ solution }}</p>
<p class="result correct">Correct! Answer: {{ solution }}</p>
</form>

With the Following CSS

.result {
    display: none;
}
.answer:checked ~ .result.incorrect{
    display: block;
    color: red;
}
.answer.solution:checked ~ p.result.correct {
    display: block;
    color: green;
}

.answer.solution:checked ~ p.result.incorrect {
    display: none;
}

And the following route

def quiz(request):
    question = "What is 2 + 2?"
    solution = "4"
    answers = [solution, "22", "NaN", "0"]
    random.shuffle(answers)
    return render(request, 'foobar/quiz.html', context=locals())

You would get a result like this jsfiddle

πŸ‘€sytech

2πŸ‘

I agree with @Sapna-Sharma and @albar comment.

You may use a simple CSS class to set the color to green and use a {% if [...] %} template filter to add the the CSS class only to the good answer

You may refer to Django official documentation to know how to handle template filter.

πŸ‘€A. STEFANI

0πŸ‘

I ended up solving my own problem:

I am not sure what to do as Albar’s answer helped the most.

  <div class={% if q1 == player.solution  %} "green" {% else %} "red" {% endif %}>
       <input type="radio" disabled/> {{q1}}</label>
   </div>

   <div class={% if q2 == player.solution  %} "green" {% else %} "red" {% endif %}>
        <input type="radio" disabled /> {{q2}}
    </div>

   <div class={% if q3 == player.solution  %} "green" {% else %} "red" {% endif %}>
        <input type="radio" disabled /> {{q3}}
    </div>

   <div class={% if q4 == player.solution %} "green" {% else %} "red" {% endif %}>
        <input type="radio" disabled /> {{q4}}
    </div>

And then the CSS:

<style>


.green {
  color: #00FF00; 
}

.red {
  color: red; 
}

</style>
πŸ‘€Parseltongue

Leave a comment