Django ModelForm with extra fields that are not in the model

后端 未结 7 485
甜味超标
甜味超标 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:40

    First add the field in the form

    class CreateForm(forms.ModelForm):
    
    extra_field     = forms.CharField(label = 'extra_field', required = False)
    

    Now while cleaning you data, you need to retrive the extra field from self.data NOT self.cleaned_data

    Correct:

     self.data.get('extra_field')
    

    Wrong:

     self.cleaned_data.get('extra_field')
    

提交回复
热议问题