NBajanca
NBajanca

Reputation: 3720

How to add CSS classes to Django Built-in forms

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?

Upvotes: 2

Views: 944

Answers (2)

NBajanca
NBajanca

Reputation: 3720

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'

Upvotes: 4

Daniel Roseman
Daniel Roseman

Reputation: 599470

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'

Upvotes: 3

Related Questions