Override a Django generic class-based view widget

Not sure if this affected earlier versions of Django, but in more recent versions the get_form() should have a default form_class=None when overriding that method.

The updated (Python 3, Django 2.2) example would be:

from django import forms

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

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

https://docs.djangoproject.com/en/2.2/ref/class-based-views/mixins-editing/#django.views.generic.edit.FormMixin


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.

Tags:

Django