#13141 closed (worksforme)
ModelForm can't update model like the way it is documented
| Reported by: | CNBorn | Owned by: | nobody |
|---|---|---|---|
| Component: | Uncategorized | Version: | 1.2-beta |
| Severity: | Keywords: | modelform instance | |
| Cc: | Triage Stage: | Unreviewed | |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
I want to update a model from a modelform,
In a view that handling the POST request, the code is like the following:
#If we already have the object , 'once_set' will be True, this_mapping will be this object
if request.method == 'POST':
if once_set == False:
f = MAPPING_MODEL_Form(request.POST)
if f.is_valid() == True:
f.save()
save_success = True
else:
print f.errors
save_success = False
else:
f = MAPPING_MODEL_Form(request.POST, instance=this_mapping)
if f.is_valid():
f.save()
save_success = True
else:
print f.errors
save_success = False
It goes well, but when I want to updated a existing model, instead of updating, it always creates a new model with all the new values from request.POST.
I am using Django 1.2 Beta1, I tried with Django 1.1's method (without instance;this_mapping=f.save()) but it didn't work out either.
Therefore I had to turn to this hack:
this_mapping.update(name=f.cleaned_data['name'], mail=f.cleaned_data['mail'], mobile=f.cleaned_data['mobile'])
Absolutly confirmed with the logic, object do exists and it do creates a new one instead of updating it.
Change History (2)
comment:1 by , 16 years ago
| Has patch: | unset |
|---|---|
| Resolution: | → worksforme |
| Status: | new → closed |
comment:2 by , 16 years ago
I should add - if you need any help debugging the problem, please ask on django-users.
If don't know what's going on here. ModelForm saving is a fairly fundamental part of Django's infrastructure, and it's extensively tested. You haven't provided the logic for your MAPPING_MODEL_Form, or the context in which this code is being invoked, so I can only assume that the problem exists somewhere in your own code.
Also - the usage of ModelForms hasn't changed between 1.1 and 1.2. instance was a valid argument to Django 1.1 modelforms.