使用引导程序自定义Django表单集的样式

时间:2018-12-26 10:06:11

标签: django twitter-bootstrap

模板包含一个具有9个字段的表单集。我们希望通过引导程序将表单集划分为3行(每行仅包含3个字段)来对其进行样式设置

template.html

 <table class="table">

  {{ contactperson_form.management_form }}

{% for form in contactperson_form.forms %}
    {% if forloop.first %}
 <thead>
      <tr>
         {% for field in form.visible_fields %}                                                                          
              <th>{{ field.label|capfirst }}</th>
         {% endfor %}
      </tr>
  </thead>
      {% endif %}
  {% for field in form.visible_fields %}
     <tr class="{% cycle row1 row2 %}  formset_row">

        <td>
          {# Include the hidden fields in the form #}
            {% if forloop.first %}
            {% for hidden in form.hidden_fields %}
                {{ hidden }}
               {% endfor %}
               {% endif %}
             {{ field.errors.as_ul }}
             {{ field }}
        </td>
       {% endfor %}
     </tr>
{% endfor %}

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
 <script src="{% static 'js/jquery.formset.js' %}"></script>
 <script type="text/javascript">
    $('.formset_row').formset({
       addText: 'add contact person',
       deleteText: 'remove',
       prefix: 'contactperson_set'
    });
  </script>

1 个答案:

答案 0 :(得分:0)

如果您将{{ field }}包装在引导程序类中,则表单字段将连续渲染3列

<div class="col-md-4">
    {{ field }}
</div>

,并省略trtd。只需使用引导网格系统即可。