Search code examples
pythoncssdjangoinline-formset

Django Add CSS to InlineFormSet


I am trying to add some CSS data to an inline formset I created. I have done it before to regular ModelForms but it is not working for the inline formset.

Here is the custom __init__:

class CustomSubIFormset(BaseInlineFormSet):
    def __init__(self, *args, **kwargs):
        super(CustomSubIFormset, self).__init__(*args, **kwargs)
        self.forms.widget.attrs.update({'placeholder': 'User Name'})

        for name, forms in self.forms.items():
            forms.widget.attrs.update({'class': 'form-control'})

The call in views.py

subIFormSet = inlineformset_factory(Study, SubInvestigator, fields=('name',), extra=4, formset=CustomSubIFormset)

The error message is 'list' object has no attribute 'widget'. Traceback:

Traceback:
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/RickyD/PycharmProjects/StudyTrack/studies/views.py" in create_study
  63.         formset = subIFormSet(instance=Study())
File "/Users/RickyD/PycharmProjects/StudyTrack/studies/forms.py" in __init__
  56.         self.forms.widget.attrs.update({'placeholder': 'User Name'})

Exception Type: AttributeError at /studies/create-study/
Exception Value: 'list' object has no attribute 'widget'

Solution

  • Try this instead:

    for form in self.forms:
       for field in form.fields:
          field.widget.attrs.update({'class': 'form-control'})