简体   繁体   中英

Django Template rendering from for loop

I have a simple form with a field names as company_name, location, country and few more which I am rendering from views.py as {'form':form} .

The usual way to call the form on the template is {% for field in form %} which is rendering the fields in the order of field attribute in the form.py file. Another way to add special classes and styles to each field I am calling every field with name as {{ form.company_name }} .

I have a another for loop which only contains the names of the form fields {% for element in fieldnames %} .

I want to render the form field as per the order in the fieldnames. I tried allot with the below example but not working.

{% for element in fieldnames %}
{{ form.element }}
{% endfor %}

Why cant we render like above using for loop but if I replace element name with the field name like {{ form.company_name }} its working

{% for name in fieldnames %}
    {% for field in form %}
        {% if field.name == name %}
            {{ field }}
        {% endif %}
    {% endfor %}
{% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM