2

I'm using Django Built-in forms, more precisely the PasswordChangeForm.

It works perfectly until the point where I want it to look like the rest of the website (Bootstrap). I followed the approach in this answer that is inheriting the class and built a new one by myself:

class PasswordChangeCustomForm(PasswordChangeForm):
    old_password = CharField(required=True,
                  widget=PasswordInput(attrs={
                    'class': 'form-control'}))

    new_password1 = CharField(required=True,
                  widget=PasswordInput(attrs={
                    'class': 'form-control'}))

    new_password2 = CharField(required=True,
                  widget=PasswordInput(attrs={
                    'class': 'form-control'}))

But it annoys me to repeat all this code. Is there another way to achieve the same thing (add the class form-control to the each field) without re-writing each field?

Community
  • 1
  • 1
NBajanca
  • 3,544
  • 3
  • 26
  • 53

2 Answers2

4

With the objective of not re-writing the fields, I found out that I could simply update the Widget:

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'})

Particularly useful for Bootstrap (where all fields need the class form-control) is the answer from @daniel-roseman:

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'
Dunatotatos
  • 1,706
  • 15
  • 25
NBajanca
  • 3,544
  • 3
  • 26
  • 53
3

You can take your code one step further and update all the widgets automatically:

super(PasswordChangeCustomForm, self).__init__(*args, **kwargs)
for field in self.fields.values():
    field.widget.attrs['class'] = 'form-control'
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895