How to remove a field from the parent Form in a subclass?

apelliciari picture apelliciari · Mar 21, 2013 · Viewed 19.6k times · Source
class LoginForm(forms.Form):
    nickname = forms.CharField(max_length=100)
    username = forms.CharField(max_length=100)
    password = forms.CharField(widget=forms.PasswordInput)


class LoginFormWithoutNickname(LoginForm):
    # i don't want the field nickname here
    nickname = None #??

Is there a way to achieve this?

Note: i don't have a ModelForm, so the Meta class with exclude doesn't work.

Answer

garnertb picture garnertb · Mar 21, 2013

You can alter the fields in a subclass by overriding the init method:

class LoginFormWithoutNickname(LoginForm):
    def __init__(self, *args, **kwargs):
        super(LoginFormWithoutNickname, self).__init__(*args, **kwargs)
        self.fields.pop('nickname')