How do I iterate over the options of a SelectField in a template?

前端 未结 5 893
长情又很酷
长情又很酷 2020-12-23 20:47

I have a select field in the form and now I need to iterate over options in this field.

{{ form.myselect }} gives me this:


        {% for id, name in form.myselect.field.choices %}
        
        {% endfor %}
    

BUT REALLY, a better way to do this is with django-widget-tweaks:

    {% load widget_tweaks %}
    {{ form.myselect|add_class:"i-can-haz-custom-classes-easily" }}

Doing it with django-widget-tweaks will also set the default 'selected="selected"' for you, which is super nice!

提交回复
热议问题