[Django]-Django adding an attribute to a model formset

3👍

You’re trying to set the fields attribute on the formset. You need to set it on the form class, not the formset class.

So, you want something like…

class ItemUserDetailsForm(forms.ModelForm):
    class Meta:
        model = CartItemUserDetails

    def __init__(self, *args, **kwargs):
        super(ItemUserDetailsForm, self).__init__(*args, **kwargs)
        self.fields['first_name'].widget = forms.TextInput(attrs={ 'class': 'required' })
        # [...]

ItemUserDetailsFormset = modelformset_factory(CartItemUserDetails, 
    form=ItemUserDetailsForm, 
    exclude=['cart', 'cart_item'],
)

Sadly, I scanned the docs and didn’t see documentation of the form keyword argument in the Django docs, but it’s clearly presented if you look at the modelform_factory function itself (see line 371).

Also, if the only thing that you’re changing is the widget property, and if you’re using Django >= 1.2 (which you should be), there’s a slightly simpler syntax on the form itself:

class ItemUserDetailsForm(forms.ModelForm):
    class Meta:
        model = CartItemUserDetails
        widgets = {
            'first_name': forms.TextInput(attrs={ 'class': 'required' }),
            # [...]
        }

Leave a comment