django bootstrap4 form snippets

Django -- Posted on March 21, 2021

The provided Python code defines a custom form and formset classes for creating Bootstrap-styled forms and formsets in Django. Let's go through each class and function to understand what they do:

  1. BootstrapForm:

    • This class is intended to be a custom form class for creating Bootstrap-styled forms.
    • It overrides the __init__ method to modify the widget attributes for fields that do not have specific widgets (CheckboxInput, ClearableFileInput, or FileInput).
    • The form-control class is added to the widget attributes of those fields to apply Bootstrap styling.
  2. BootstrapFormSet:

    • This class is intended to be a custom formset class for creating Bootstrap-styled formsets in Django.
    • It inherits from BaseInlineFormSet, which is a Django formset that handles inline formsets.
    • It also overrides the __init__ method to modify the widget attributes for fields that do not have specific widgets (CheckboxInput, ClearableFileInput, or FileInput) in each form of the formset.
    • The form-control class is added to the widget attributes of those fields to apply Bootstrap styling.
    • Additionally, it overrides the add_fields method, which is called to add fields to a form. It performs similar modifications to the widget attributes of fields in the form.
  3. unique_bootstrap_field_formset(field_name):

    • This is a factory function that returns a new class, UniqueFieldBootstrapFormSet, which is a subclass of BootstrapFormSet.
    • The purpose of this factory function is to create a formset that ensures a specific field's values are unique across all forms in the formset.
    • The clean method is overridden to perform this validation by checking if the field values are unique.
    • If any form has errors (e.g., individual form validation fails), the clean method returns early without performing the unique validation.
    • If a non-unique value is found for the specified field_name, the form's field is marked as invalid, and an error message is added to the form.

Overall, this code snippet provides a way to create Bootstrap-styled forms and formsets in Django and includes a custom validation to ensure that a specified field's values are unique in the formset.

Keep in mind that the implementation assumes the existence of self.fields and self.forms, which should be available in the actual implementation of the Django form and formset classes. Also, the code provided assumes that the necessary imports have been made elsewhere in the codebase (e.g., BaseInlineFormSet and other required Django modules).

 

              
                class BootstrapForm:
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        fields = ['CheckboxInput', 'ClearableFileInput', 'FileInput']
        for field in self.fields:
            widget_name = self.fields[field].widget.__class__.__name__
            if widget_name not in fields:
                self.fields[field].widget.attrs.update({
                    'class': 'form-control'
                })


class BootstrapFormSet(BaseInlineFormSet):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        fields = ['CheckboxInput', 'ClearableFileInput', 'FileInput']
        for form in self.forms:
            for field in form.fields:
                widget_name = form.fields[field].widget.__class__.__name__
                if widget_name not in fields:
                    form.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 in form.fields:
            widget_name = form.fields[field].widget.__class__.__name__
            if widget_name not in fields:
                form.fields[field].widget.attrs.update({
                    'class': 'form-control'
                })


def unique_bootstrap_field_formset(field_name):
    class UniqueFieldBootstrapFormSet(BootstrapFormSet):
        def clean(self):
            if any(self.errors):
                # Don't bother validating the formset unless each form is valid on its own
                return
            values = set()
            for form in self.forms:
                if form.cleaned_data:
                    value = form.cleaned_data.get(field_name)
                    if value:
                        if value in values:
                            form[field_name].field.widget.attrs['class'] += ' is-invalid'
                            form.add_error(field_name, "{} {} cannot be added multiple times.".format(
                                field_name, value))
                        values.add(value)
    return UniqueFieldBootstrapFormSet
                  
   
            

Related Posts