Django form field grouping

后端 未结 3 444
说谎
说谎 2020-12-30 09:23

Say I have a form with 20 fields, and I want to put 10 of these fields (group1) in a particular div environment and the other 10 fields (group2) in a different div environme

3条回答
  •  灰色年华
    2020-12-30 10:04

    Any logical way to group fields would work... say you have a method on your form that returns form fields that you explicitly group?

    To save typing, perhaps a certain field prefix naming scheme?

    class MyForm(forms.Form):
        group1_field = forms.CharField()
        group1_field = forms.CharField()
        group2_field = forms.CharField()
        group2_field = forms.CharField()
    
       def group1(self):
            return [self[name] for name in filter(lambda x: x.startswith('group1_'), self.fields.values()]
    

    Perhaps set an attribute on the field you can filter by?

    class MyForm(forms.Form):
        field = forms.CharField()
        field.group = 1
    
        field2 = forms.CharField()
        field2.group = 2
    
        def group1(self):
            return filter(lambda x: x.group == 1, self.fields.values())
    
        def group2(self):
            return filter(lambda x: x.group == 2, self.fields.values())
    

    You could also use the regroup tag if you set these attributes.

    {% regroup form.fields by group as field_group %}
    {% for group in field_group %}
    
    {% for field in group.list %} {{ field }} {% endfor %}
    {% endfor %}

提交回复
热议问题