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
- [Django]-Inverted logic in Django ModelForm
- [Django]-A production ready server to serve django on win32
- [Django]-How to see exceptions raised from a channels consumer
- [Django]-Image is not uploaded via django form
- [Django]-Saving inlineformset in Django class-based views (CBV)
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
- [Django]-How to reference a slug from a different model in get_success_url?
- [Django]-Sphinx Note Block in a list under a code block?
- [Django]-Type object 'Post' has no attribute 'published' Django
- [Django]-Django custom templatetag not getting request in context
Source:stackexchange.com