django - 使用FormView和ModelForm更新模型 [英] django - update model with FormView and ModelForm

查看:439
本文介绍了django - 使用FormView和ModelForm更新模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何使用 FormView 中的 ModelForm ,以便更新已有的

I can't figure out how to use a ModelForm in a FormView so that it updates an already existing instance??

此URL上的POST表单: r'/ object /(?P< pk>)/'

The form POSTs on this URL: r'/object/(?P<pk>)/'

我使用一个 ModelForm (而不是直接 UpdateView ),因为其中一个字段是必需的,我执行一个干净。

I use a ModelForm (and not directly an UpdateView) because one of the fields is required and I perform a clean on it.

我基本上想提供kwarg 实例= ... 当初始化 FormView (在POST时)中的表单,以便绑定到该URL在该URL中给出的对象。但是我不知道该怎么做...

I'd basically like to provide the kwarg instance=... when initializing the form in the FormView (at POST) so that it's bound to the object whose pk is given in the url. But I can't figure out where to do that...

class SaveForm(ModelForm):
    somedata = forms.CharField(required=False)
    class Meta:
        model = SomeModel  # with attr somedata
        fields = ('somedata', 'someotherdata')
    def clean_somedata(self):
        return sometransformation(self.cleaned_data['somedata'])

class SaveView(FormView):
    form_class = SaveForm
    def form_valid(self, form):
        # form.instance here would be == SomeModel.objects.get(pk=pk_from_kwargs)
        form.instance.save()
        return ...


推荐答案

经过与你的讨论,我还是不明白为什么你不能使用的UpdateView 。如果我正确理解,这似乎是一个非常简单的用例。您有一个要更新的模型。并且您有一个自定义窗体进行清洁,然后将其保存到该模型。似乎像 UpdateView 将工作正常。像这样:

After some discussion with you, I still don't see why you can't use an UpdateView. It seems like a very simple use case if I understand correctly. You have a model that you want to update. And you have a custom form to do cleaning before saving it to that model. Seems like an UpdateView would work just fine. Like this:

class SaveForm(ModelForm):
    somedata = forms.CharField(required=False)

    class Meta:
        model = SomeModel  # with attr somedata
        fields = ('somedata', 'someotherdata')

    def clean_somedata(self):
        return sometransformation(self.cleaned_data['somedata'])


class SaveView(UpdateView):
    template_name = 'sometemplate.html'
    form_class = SaveForm
    model = SomeModel

    # That should be all you need. If you need to do any more custom stuff 
    # before saving the form, override the `form_valid` method, like this:

    def form_valid(self, form):
        self.object = form.save(commit=False)

        # Do any custom stuff here

        self.object.save()

        return render_to_response(self.template_name, self.get_context_data())

当然,如果我误会你,请让我知道。你应该能够让它上班。

Of course, if I am misunderstanding you, please let me know. You should be able to get this to work though.

这篇关于django - 使用FormView和ModelForm更新模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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