在Django ModelForm中保存自定义字段 [英] Save custom field in Django ModelForm

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

问题描述

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

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

我添加了 save()方法,如

I have added a save() method as shown in this question. However, when I use it I get an error:

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

ImproperlyConfigured
No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model.

当我删除自定义的 save()方法时,它可以正常运行,但不保存自定义字段.我想念什么?

When I remove my custom save() method it works ok but doesn't save the custom field. What am I missing?


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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆