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

前端 未结 4 1990
太阳男子
太阳男子 2020-12-06 03:57
class LoginForm(forms.Form):
    nickname = forms.CharField(max_length=100)
    username = forms.CharField(max_length=100)
    password = forms.CharField(widget=form         


        
4条回答
  •  星月不相逢
    2020-12-06 04:35

    I didn't like the fact (or so I understood) that the exclusion of a field in the second class using "class Meta:" still results in the unused field being in the db.

    Perhaps the simplest way is to define an abstract class that has the fields shared by both classes. Then the two original classes above become subclasses of this new class. So the example given at the start of this thread might look the following. It's a bit more code, but this way you extend a subclass rather than do an (incomplete) exclusion from a super class.

    class LoginForm_Common(forms.Form):
        username = forms.CharField(max_length=100)
        password = forms.CharField(widget=forms.PasswordInput)
        class Meta:
            abstract = True
    
    class LoginForm(LoginForm_Common):
        nickname = forms.CharField(max_length=100)
    
    class LoginFormWithoutNickname(LoginForm_Common):
        pass
    

提交回复
热议问题