4m1nh4j1
4m1nh4j1

Reputation: 4356

Django password field custom class

I would like to render the password field with a custom class, so I tried this:

from django.contrib.auth import get_user_model
from django.db import transaction
User = get_user_model()

class SignupForm(forms.ModelForm):

    first_name = forms.CharField(label=_(u'First name'), max_length=30)
    last_name = forms.CharField(label=_(u'Last name'), max_length=30)
    password1 = forms.CharField(widget = forms.PasswordInput(render_value = True, attrs={'class': 'form-control', 'placeholder': 'Your password'}))


    def __init__(self, *args, **kwargs):
        super(SignupForm, self).__init__(*args, **kwargs) 
        self.fields['username'].widget.attrs.update({'class': 'form-control', 'placeholder': 'Your username'})
        self.fields['first_name'].widget.attrs.update({'class': 'form-control', 'placeholder': 'Your first name'})
        self.fields['last_name'].widget.attrs.update({'class': 'form-control', 'placeholder': 'Your last name'})
        self.fields['email'].widget.attrs.update({'class': 'form-control', 'placeholder': 'Your email address'})
        self.fields['password1'].widget.attrs.update({'class': 'form-control', 'placeholder': 'Your password'})

As you may notice, I tried to add the class on the declaration and in the initialization but none of this works. The class is still the default one.

Note that for email, username, and the other fields, the class/placeholder are working fine. Am I missing something?

EDIT: This will probably help in diagnosing the problem. This is what I use in HTML:

                    <div class="col-md-6">
                        <br />
                        <div class="form-group">
                            <label for="password1">{{ form.password1.label }}</label>  
                            {{ form.password1 }}    
                            {% if form.password1.errors %}
                                <div class="text-danger">{{ form.password1.errors|escape }}</div>   
                            {% endif %}                             
                        </div>
                    </div>

Upvotes: 3

Views: 2317

Answers (2)

Jakub Holan
Jakub Holan

Reputation: 421

Ngawang13's answer solved the issue in the questions for me - i.e. the class was set to form-control.

However, to expand on Ngawang13's answer, if you wanted to use this field in multiple places, you could create a custom field class.

class MyCustomPasswordField(forms.CharField):
    def __init__(self, **kwargs,):
        self.widget = forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'})
        super().__init__(**kwargs)

Upvotes: 0

ngawang13
ngawang13

Reputation: 673

You can do this directlly without the init method

 password1 = forms.CharField(widget=forms.PasswordInput(
    attrs={'class':'form-control','type':'password', 'name': 'password','placeholder':'Password'}),
    label='')

Upvotes: 4

Related Questions