ModelForm中保存自定义字段

ModelForm中保存自定义字段

本文介绍了在Django ModelForm中保存自定义字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在ModelForm中保存自定义字段.有问题的字段是ModelChoiceField.

I am having trouble saving a custom field in a ModelForm. The field in question is a ModelChoiceField.

我添加了 save()方法,如class NewStoryForm(forms.ModelForm): class Meta: model = Story fields = ['title', 'story_text'] #custom field about = forms.ModelChoiceField(queryset=None) #initialise custom field def __init__(self, user, *args, **kwargs): super(NewStoryForm, self).__init__(*args, **kwargs) self.fields['about'] = forms.ModelChoiceField(queryset=Experience.objects.filter(user=user)) #save custom field def save(self, commit=True): self.instance.about = self.cleaned_data['about'] super(NewStoryForm, self).save(commit=commit) class NewStoryView(CreateView): form_class = NewStoryForm template_name = 'story/story_form.html' #Send user to NewStoryForm to initialise custom field def get_form_kwargs(self): kwargs = super(NewStoryView, self).get_form_kwargs() kwargs['user'] = self.request.user return kwargs #save author as current user def form_valid(self, form): form.instance.author = self.request.user return super(NewStoryView, self).form_valid(form)

推荐答案

您应该通过 save()方法返回保存的对象:

You should return the saved object from the save() method:

return super(NewStoryForm, self).save(commit=commit)

这篇关于在Django ModelForm中保存自定义字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!