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>
<div class="col-12 mt-4">
{{ form.password2 }}
</div>
But the result for the Password field is not styled as the other fields. The rendered register page is as shown below
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'}
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. https://django-crispy-forms.readthedocs.io/en/latest/