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中保存自定义字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!