Override BaseInline Formset

Django -- Posted on March 20, 2021

The code you provided seems to define a custom formset called BootstrapFormSet that inherits from Django's BaseInlineFormSet. This custom formset is intended to add the 'form-control' class to form fields' widgets, except for specific widgets listed in the fields list.

The purpose of this formset might be to apply Bootstrap styles to form fields while excluding certain widgets from this styling.

Let's go through the code step by step:

  1. The BootstrapFormSet class is defined, inheriting from BaseInlineFormSet.

  2. In the __init__ method, the class iterates through each form instance in the formset and then iterates through each field in the form. For each field, it checks the widget's class name, and if it is not in the fields list (i.e., not a 'CheckboxInput', 'ClearableFileInput', or 'FileInput'), it adds the 'form-control' class to the field's widget attributes. This is done to style the form fields with Bootstrap.

  3. The add_fields method is overridden to achieve the same result as in the __init__ method. This method is called for each form instance when fields are added to the form during the formset's initialization.

Overall, this custom formset aims to apply the 'form-control' class to form fields' widgets, except for certain widgets specified in the fields list, likely to preserve their default styling.

 

              
                from django.forms import BaseInlineFormSet

class BootstrapFormSet(BaseInlineFormSet):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        fields = ['CheckboxInput', 'ClearableFileInput', 'FileInput']
        for form in self.forms:
            for field_name, field in form.fields.items():  # Corrected iteration to access field instances
                widget_name = field.widget.__class__.__name__
                if widget_name not in fields:
                    field.widget.attrs.update({
                        'class': 'form-control'
                    })

    def add_fields(self, form, index):
        super().add_fields(form, index)
        fields = ['CheckboxInput', 'ClearableFileInput', 'FileInput']
        for field_name, field in form.fields.items():  # Corrected iteration to access field instances
            widget_name = field.widget.__class__.__name__
            if widget_name not in fields:
                field.widget.attrs.update({
                    'class': 'form-control'
                })
                  
   
            

Related Posts