Reading radio button value inside template

Hi all,

Beginner here. I have the following view code snippet for a test project :

def index(request):
    template = loader.get_template("cars/index.html")
    filter = request.POST.get("filter", "id_none")
    context = {
        "list_cars": CarBrand.objects.all(),
        "filter_list_colors": CarColor.objects.all(),
        "filter": filter
    }
    return HttpResponse(template.render(context, request))

And the related template part (inside a form):

{% for color in filter_list_colors %}
<input type="radio" id= "id_color{{color.id}}" name="filter" value="val_color{{color.id}}"
	{% if filter == "???" %} checked {% endif %}>
	<label for="id_color{{color.id}}">{{color.color_name}}</label>
	<br/>
{% endfor %}

My question is, what to use in place of the "???" above ? I want to say: “If context variable filter is matching this radio button’s value, set it to checked”.

So, you will need to compare the filter context variable with the value of the radio button in your template.
Try something like this:

{% for color in filter_list_colors %}
    <input type="radio" id="id_color{{ color.id }}" name="filter" value="val_color{{ color.id }}"
        {% if filter == "val_color{{ color.id }}" %} checked {% endif %}>
    <label for="id_color{{ color.id }}">{{ color.color_name }}</label>
    <br/>
{% endfor %}

`