izdi
izdi

Reputation: 565

Using CBV form_invalid() method to update Model object

I want to update existing object in the Model. But I am using form_invalid(self, form) for this.

**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'),

I create new objects in my model the same way in my other class, but however I cant update it and I get this error:

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

Upvotes: 0

Views: 97

Answers (1)

Rod Xavier
Rod Xavier

Reputation: 4043

It's because get() does not return a queryset. Instead, it returns an instance of the model.

Try replacing

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

with

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

Read the Queryset API reference for more info.

Upvotes: 2

Related Questions