Django ModelForm with extra fields that are not in the model

后端 未结 7 406
甜味超标
甜味超标 2021-01-31 02:00

I have done a ModelForm adding some extra fields that are not in the model. I use these fields for some calcualtions when saving the form.

The extra fie

7条回答
  •  鱼传尺愫
    2021-01-31 02:32

    I had a very similar problem except it looked like I did all the required thing, but I was getting this error when Django was starting:

    django.core.exceptions.FieldError: Unknown field(s) (my_new_field) specified for MyModel
    

    This was a silly mistake from me, I accidentally declared my field using a Widget class:

    class MyForm(forms.ModelForm):
        my_new_field = forms.HiddenInput()
    

    Instead of a Field class:

    class MyForm(forms.ModelForm):
        my_new_field = forms.CharField(widget=forms.HiddenInput())
    

    Not answering the question at hand here (which is answered well already), but might help others.

提交回复
热议问题