markin jason
markin jason

Reputation: 60

how do i set radio button as checked based on database values in django template?

here is my html code

<input type="radio" name="cast" id="open" style="margin-left:10px;text-align:left;" value="Open" {% if data.cast %}checked{% endif %} required>Open
                    <input type="radio" name="cast" id="sebc" style="margin-left:10px;text-align:left;" value="SEBC" {% if data.cast %}checked{% endif %} required>SEBC
                    <input type="radio" name="cast" id="sc/st" style="margin-left:10px;text-align:left;" value="SC/ST" {% if data.cast %}checked{% endif %} required>SC / ST
                    <input type="radio" name="cast" id="other" style="margin-left:10px;text-align:left;" value="Other" {% if data.cast %}checked{% endif %} required>Other

I did this but it didn't work for me. the data.cast is variable having database value.

Upvotes: 2

Views: 1323

Answers (1)

Maisum Abbas
Maisum Abbas

Reputation: 359

Even though it's late to answer it, I was having the same issue just now. You will have to compare it in terms of value but it's not a good practice especially when there's a lot of radio options to do it with.

<input type="radio" name="cast" id="open" style="margin-left:10px;text-align:left;" value="Open" {% if data.cast != 'SEBC' and data.cast != 'SC/ST' and data.cast != 'Other' %} checked {% endif %} required>Open
<input type="radio" name="cast" id="sebc" style="margin-left:10px;text-align:left;" value="SEBC" {% if data.cast != 'Open' and data.cast != 'SC/ST' and data.cast != 'Other' %} checked {% endif %} required>SEBC
<input type="radio" name="cast" id="sc/st" style="margin-left:10px;text-align:left;" value="SC/ST" {% if data.cast != 'SEBC' and data.cast != 'Open' and data.cast != 'Other' %} checked {% endif %} required>SC / ST
<input type="radio" name="cast" id="other" style="margin-left:10px;text-align:left;" value="Other" {% if data.cast != 'SEBC' and data.cast != 'SC/ST' and data.cast != 'Open' %} checked {% endif %} required>Other

Note: I have also tried it with just this:

{% if data.cast == 'yourvalue' %} checked {% endif %}

But, for some reason this doesn't work.

Upvotes: 1

Related Questions