在Django ModelForm中保存自定义字段

时间:2015-03-18 08:39:18

标签: django modelform

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

我添加了save()方法,如this问题所示。但是,当我使用它时,我收到一个错误:

  

不正确的配置
  没有要重定向到的网址。在模型上提供URL或定义get_absolute_url方法。

当我删除自定义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)

1 个答案:

答案 0 :(得分:1)

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

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