Django: For Loop to Iterate Form Fields

前端 未结 4 1000
半阙折子戏
半阙折子戏 2021-02-07 10:09

I don\'t want to use django\'s built in form generation, seeking to specify each field in my template in order to customize the html output.

How do I iterate over a ser

相关标签:
4条回答
  • 2021-02-07 10:50

    Well this would clearly not work:

    {% for field in form %}
        {{ form.field }}
    {% endfor %}
    

    but this will:

    {% for field in form %}
        {{ field }}
    {% endfor %}
    
    0 讨论(0)
  • 2021-02-07 10:53

    The best way is to use two loops, one for hidden fields and one for visible fields :

    visibles:

    {% for field in form.visible_fields %}
        {{ field.label }}
        {{ field }}
    {% endfor %}
    

    hiddens:

    {% for hidden in form.hidden_fields %}
        {{ hidden }}
    {% endfor %}
    

    in this way you will have better control over UI elements.

    0 讨论(0)
  • 2021-02-07 11:07

    This one should work :

    {% for field in form %}
      {{ field }}
    {% endfor %}
    

    Once you loop through field in form , you can't access form.field

    0 讨论(0)
  • 2021-02-07 11:09

    For any frontend developers looking to customize a Django form you can use a package called django-widget-tweaks to render fields individually. Example code below:

    {# Your template with the form #}
    {% extends "base.html" %}
    {% load widget_tweaks %}
    
    <form action="" method="POST">
        {% csrf_token %}
    
        {% for field in form %}
            <label for="{{ field.id_for_label }}">
              {{ field.label }}{% if field.field.required %}*{% endif %}
            </label>
            {% render_field field %}
        {% endfor %}
    
        <button type="button">
            Submit Form
        </button>
    </form>
    

    Note: You'll want to make this look nicer of course, and you may want to loop through your form errors if there are any.

    They have some very useful examples on their PyPi page as well.

    0 讨论(0)
提交回复
热议问题