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?

2 Answers 2

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'
Sign up to request clarification or add additional context in comments.

Comments

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'

1 Comment

Your code gives a AttributeError 'str' object has no attribute 'widget'. I resolved it in mine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.