The Python Oracle

Django: How to apply conditional attribute to HTML element in template?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle4

--

Chapters
00:00 Question
01:02 Accepted answer (Score 13)
01:15 Answer 2 (Score 23)
01:29 Thank you

--

Full question
https://stackoverflow.com/questions/2864...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #django #python27 #djangotemplates

#avk47



ANSWER 1

Score 24


Why not wrap the attribute in a conditional?

<input type="checkbox" name="sendEmail" {% if customer.SendSms %}checked{% endif %}>



ACCEPTED ANSWER

Score 15


yesno template filter will do the job:

<input type="checkbox" name="sendSms" {{ customer.SendSms|yesno:"checked" }}>