Django split model form fields into bootstrap rows

Django -- Posted on Aug. 8, 2023

Django doesn't provide a built-in way to split a ModelForm's fields into multiple rows by default. However, you can achieve this by customizing the rendering of the form in the template. Here's how you can dynamically split the fields into rows.

In the template pass a modelform as argument.

 

              
                template tag 

from django import template
register = template.Library()


@register.inclusion_tag("custom_form.html")
def generate_form(form):
    return {"form": form}





<!-- templates/myapp/custom_form_template.html -->
{% for hidden in form.hidden_fields %}
  {{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
        <div class="col">
            <label for="{{field.id_for_label}}" class="form-label">{{field.label}}</label>
            {{field}}
            <div class="invalid-feedback">
                {{field.errors}}
            </div>
            {% if field.help_text %}
                <p class="help">{{ field.help_text|safe }}</p>
            {% endif %}
        </div>
        {% if forloop.counter0|divisibleby:3 %}
        {# Start new row #}
        </div>
        <div class="row g-3">
        {% endif %}
{% endfor %}
<div class="row py-2">
  <div class="d-grid gap-2 d-md-flex justify-content-md-end">
    <a href="{{back_url}}" class="btn btn-link">Back</a>
  <button type="submit" name="button" class="btn btn-primary">Save</button>
</div>
</div>
                  
   
            

Related Posts