Julio
Julio

Reputation: 2523

Django field display in template by group

I would like to display 2 groups of fields. The group is defined based on the kind of field.

I added 2 methods in my form:

def get_group_a(self):
    return [obj for obj in self.fields.values() if isinstance(obj, GroupAField)]

def get_group_b(self):
    return [obj for obj in self.fields.values() if isinstance(obj, GroupBField)]

Then in the template I tried to display the form:

<h1>Group A:</h1>
{% for f in form.get_group_a %}
    <div class="fieldWrapper">
        {{ f.errors }}
        <label> {{ f.label }}:</label>
        {{ f }}
    </div>
{% endfor %}

<h1>Group B:</h1>
{% for f in form.get_group_b %}
    <div class="fieldWrapper">
        {{ f.error }}
        <label> {{ f.label }}:</label>
        {{ f }}
    </div>
{% endfor %}

This is working partially. I have the good label of the field but I don't have the text input displayed.

How can I get the good field object?

Upvotes: 1

Views: 244

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599778

Don't iterate through self.fields in your get_group methods, but through self directly. self.fields contains the raw field instances: for display, Django creates BoundField instances which wrap those fields, and which you access directly via self['fieldname'].

Upvotes: 1

Alex Lisovoy
Alex Lisovoy

Reputation: 6065

For representing form fields in template Django uses BoundField. BoundField used to display HTML or access attributes for a single field of a Form instance. So in your case, you should wrap grouped fields with BoundField, like this:

def get_group_a(self):
    return [BoundField(self, field, name) for name, field in self.fields.items() if isinstance(field, GroupAField)]

def get_group_b(self):
    return [BoundField(self, field, name) for name, field in self.fields.items() if isinstance(field, GroupbField)]

Upvotes: 1

Related Questions