1

How can one insert markup between subsets of form fields in django, while staying DRY?

Given:

class CompensationUpdate(UpdateView):
    model = Compensation
    fields = [
        'salary1',
        'salary2',
        'incentive1',
        'incentive2', ]

I'd like to be able to access them in the view in such a way that I can wrap groups of them in markup. For example:

<div class="ibox-content">
    {% for field in form.salary_fields %}
        ...
    {% endfor %}
</div>
<div class="ibox-content">
    {% for field in form.incentive_fields %}
        ...
    {% endfor %}
</div>

I have over 50 fields on the form in about 10 groups, so I need to do this in a DRY manner. While I can access each field individually, I can't figure out how to define subsets (either in the UpdateView or directly in the template).

Brian Olpin
  • 87
  • 1
  • 9

1 Answers1

2

You can use django-betterforms, which has FieldSets that you can group your fields in.

In your Meta class on your form, you specify FieldSets of grouped fields:

class Meta:
    fieldsets = (
        ('info', {'fields': ('username', 'email')}),
        ('location', {'fields': ('address', ('city', 'state', 'zip'))}),
        ('password', {'password1', 'password2'}),
    )

And in the template you can iterate over the FieldSets

{% for fieldset in form %}
    <div class="ibox-content">
        {% for field in fieldset %}
            ...
        {% endfor %}
    </div>
{% endfor %}

You can see more of the proposed template implementation here.

Other solutions are this answer or django-form-utils which is a better documented version of my answer. The latter however seems to be unmaintained today, but could work depending on your Django Version.

Johan
  • 3,577
  • 1
  • 14
  • 28