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

前端 未结 4 1984
太阳男子
太阳男子 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条回答
  •  Happy的楠姐
    2020-12-06 04:47

    I found that, please comment if interested.

    (in Django 1.7.4) extending forms, with following code:

    class MyForm(forms.ModelForm):
    
        def __init__(self, *args, **kwargs):
            super(MyForm, self).__init__(*args, **kwargs)
    
            for key, field in self.fields.iteritems():
                self.fields[key].required = False
    
        class Meta:
            model = MyModel
            exclude = []
    
        field_1 = forms.CharField(label="field_1_label")
        field_2 = forms.CharField(label="field_2_label", widget=forms.Textarea(attrs={'class': 'width100 h4em'}),)
        field_3 = forms.CharField(label="field_3_label", widget=forms.TextInput(attrs={'class': 'width100'}),)
        field_4 = forms.ModelChoiceField(label='field_4_label', queryset=AnotherModel.objects.all().order_by("order") )
    
    class MyForm_Extended_1(MyForm):
        field_1 = None
    
    
    class MyForm_Extended_2(MyForm):
        class Meta:
            model = MyModel
            exclude =[
                        'field_1',
                    ]
    

    MyForm_Extended_1 set field_1 as None, (the column in db is updated as Null)

    MyForm_Extended_2 ignore the field (ignore the column in db during the save)

    So, for my purpose, I use the second method.

提交回复
热议问题