Questions & Answers

Django Password Field Not Rendering with Bootstrap Attributes

I was trying to style my password fields in the registration of my Django Accounts App.

'password1': forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password','required': 'required'}, ),
'password2': forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Confirm password','required': 'required'}, ),

My view renders to the register.html which is in the code below

<div class="col-12 mt-4">
    {{ form.password1 }}
<div class="col-12 mt-4">
    {{ form.password2 }}

But the result for the Password field is not styled as the other fields. The rendered register page is as shown below
rendered register.html page

What could be the fix to give the following output expected output

Answers(3) :

I would suggest like this: Please try this.

Method 1

password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password','required': 'required'}, ))
password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Confirm password','required': 'required'}, ))

Method 2

Using constructor (Reduce code)

def __init__(self, *args, **kwargs):
    super(SignUpForm, self).__init__(*args, **kwargs)
    self.fields['username'].widget.attrs = {'class': 'form-control', 'placeholder': 'Password','required': 'required'}
    self.fields['password1'].widget.attrs = {'class': 'form-control', 'placeholder': 'Confirm password','required': 'required'}
    self.fields['password2'].widget.attrs = {'class': 'form-control', 'placeholder': 'Confirm password','required': 'required'}
2023-01-11 09:10:49
I was able to fix it using the constructor, turns out the default fields from django i.e username, password1 and password2 widgets can be enhanced at the constructor..Here is the code

After research, it turns out the default Django register fields i.e "username", "password1" and "password2" widgets can be tweaked at the constructor, here is the working code

def __init__(self, *args, **kwargs):
    super(SignUpForm, self).__init__(*args, **kwargs)

    self.fields['username'].widget.attrs['class'] = 'form-control'
    self.fields['username'].widget.attrs['placeholder'] = 'Username'
    self.fields['password1'].widget.attrs['class'] = 'form-control'
    self.fields['password1'].widget.attrs['placeholder'] = 'Password'
    self.fields['password2'].widget.attrs['class'] = 'form-control'
    self.fields['password2'].widget.attrs['placeholder'] = 'Confirm password'

Try using crispy_fields or django-crispy-forms. I faced same issue but after that I implemented crispy-forms and resolved issue.