Override a Django generic class-based view widget

You could override get_form(), and modify the form to change the widget on the password field:

from django import forms

class Signup(CreateView):
    model = User
    fields = ['first_name', 'last_name', 'email', 'password']

    def get_form(self, form_class):
        form = super(Signup, self).get_form(form_class)
        form.fields['password'].widget = forms.PasswordInput()
        return form

But an even better way would be to just create a custom form class. In the custom class just set widgets on the Meta class. Like this:

from django import forms

class SignupForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'email', 'password']
        widgets = {
            'password': forms.PasswordInput()
        }

class Signup(CreateView):
    form_class = SignupForm
    model = User

Usually you would put the custom form class in a forms.py file as well.

Leave a Comment

tech