0

I'm trying to add a "form" attribute to the modelform used by a formset so that I can put my form elements into a table as described here Form inside a table

I found this answer which seems to be what I wanted How to add class, id, placeholder attributes to a field in django model forms

I've implemented this as shown in my forms.py

class EditAssemblyForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(EditAssemblyForm, self).__init__(*args, **kwargs)
        for field in self.fields:
            self.fields[field].widget.attrs.update(
                {'form': 'EditAssemblyForm'})

        self.fields['issue'].required = False
        self.fields['qty'].widget.attrs['min'] = 1
        #self.fields['id'].widget.attrs.update({'form': 'EditAssemblyForm'})

    class Meta:
        model = Relationship
        fields = ['issue', 'qty']

This is working for the issue and qty form elements but not for the hidden id field. I tried to specifically apply this to self.fields['id'] as can be seen in the commented line but this causes an error:

Exception Type: KeyError
Exception Value: 'id'
Exception Location: C:\SvnDeltaRepository\DeltaSoftware\django\delta\PaNDa\forms.py, line 98, in __init__
Chonker
  • 21
  • 4

1 Answers1

0

I ended up adding it in the views.py instead:

for form in formset:
    form.fields.get('id').widget.attrs['form'] = 'EditAssemblyForm'

Seems to work

--edit-- Also had to add:

for field in formset.management_form.fields:
            formset.management_form.fields[field].widget.attrs['form'] = 'EditAssemblyForm'

This adds the same attribute to the hidden fields that the management_form generates. Without this the formset.is_valid() would fail.

Chonker
  • 21
  • 4