使用CBV form_invalid()方法更新模型对象

2024-04-26 09:53:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我想更新模型中的现有对象。但是我用form_invalid(self, form)来做这个。你知道吗

**views.py**
class SomeClassView(UpdateView):
    model = Some
    form_class = SomeForm
    template_name = 'some.html'

    def form_invalid(self, form):
        Some.objects.get(id=self.kwargs['pk']).update(**form.cleaned_data)
        return HttpResponseRedirect(self.request.POST['redirect_url'])

**urls.py**
url(r'^edit/(?P<pk>\d+)/$', SomeclassView.as_view(), name='edit'),

我在模型中创建新对象的方式与在其他类中相同,但我无法更新它,因此出现以下错误:

AttributeError at /edit/1/
'Some' object has no attribute 'update'

Tags: 对象namepy模型selfformurlupdate
1条回答
网友
1楼 · 发布于 2024-04-26 09:53:58

这是因为get()不返回queryset。相反,它返回模型的一个实例。你知道吗

尝试替换

Some.objects.get(id=self.kwargs['pk']).update(**form.cleaned_data)

Some.objects.filter(id=self.kwargs['pk']).update(**form.cleaned_data)

阅读Queryset API reference了解更多信息。你知道吗

相关问题 更多 >