Reputation: 721
I'm trying to update an model's fields with save method:
forms.py:
class FooForm(forms.ModelForm):
class Meta:
model = Foo
exclude = ['created']
views.py:
class FooView(FormView):
success_url = '/some/url/'
template_name = 'some/template.html'
form_class = FooForm
model = Foo
def form_valid(self, form):
if 'foo' in self.request.session:
pk = self.request.session['foo']
foo = Foo.objects.get(pk=pk)
self.object = form.save(instance=foo)
else:
self.object = form.save()
self.request.session['foo'] = self.object.pk
return HttpResponseRedirect(self.get_success_url())
I have an error, when i try to use form.save(instance=foo):
TypeError at /some/url
save() got an unexpected keyword argument 'instance'
What is my problem?
Django 1.9.0
Python 3.4.3
Upvotes: 0
Views: 3098
Reputation: 721
def form_valid(self, form):
if 'foo' in self.request.session:
pk = self.request.session['foo']
foo = Foo.objects.get(pk=pk)
foo_form = self.form_class(form.cleaned_data, instance=foo)
foo_form.save()
Upvotes: 0
Reputation: 1267
You should provide an instance to the constructor of the form, not to save
method.
To make it works, you should use UpdateView.
Upvotes: 0
Reputation: 65460
If you read the very documentation that you linked, you will see that the instance
keyword is an input to the ModelForm constructor and not the save method.
You will need to do something like
form = FooForm(instance=foo)
form.save()
Upvotes: 2