Django Built-in forms

Other topics

Add custom CSS classes

Built-in forms are great but sometimes there is a need to customize them, adding new fields or simply changing CSS attributes.

This example is applicable to several use cases but here it is presented regarding PasswordChangeForm and its use in a Bootstrap website.

The solution is to create another Form that inerits PasswordChangeForm update the Widget:

class PasswordChangeCustomForm(PasswordChangeForm):
    def __init__(self, user, *args, **kwargs):
        super(PasswordChangeCustomForm, self).__init__(user,*args, **kwargs)
        for field in self.fields:
            self.fields[field].widget.attrs['class'] = 'form-control'

If you only pretend to change certain fields you may do:

class PasswordChangeCustomForm(PasswordChangeForm):
    def __init__(self, user, *args, **kwargs):
        super(PasswordChangeCustomForm, self).__init__(user, *args, **kwargs)
        self.fields['old_password'].widget.attrs.update({'class': 'form-control'})
        self.fields['new_password1'].widget.attrs.update({'class': 'form-control'})
        self.fields['new_password2'].widget.attrs.update({'class': 'form-control'})

Note: all bootstrap forms require the class form-control to keep the website look and feel.

Contributors

Topic Id: 8927

Example Ids: 27777

This site is not affiliated with any of the contributors.