Reputation: 47
Is there any easy way to change the instance of a Django model form after it's been initialised?
For example the following would pre-populate the form in a template with the contents currently in the db for the object with an id of 1:
form = exampleModelForm(instance = Model.objects.get(pk=1)
This will also save the relevant object when save() is called rather than create a new one.
Where this will create a new object and not pre-populate the form in the template:
form = exampleModelForm()
As I'm returning a blank form from a different method, I would then like to assign an instance to it after it's been created and amend the object so that it can be saved and the template is pre-populate with the values that exist in the db. I want something like this but what I've tried doesn't seem to work:
form = methodThatGetsForm(somearg)
form.instance = ExampleModel.objects.get(pk = getId(somearg))
Is there a simple function that I'm missing here?
Upvotes: 1
Views: 1881
Reputation: 8285
I have NOT tested this, but I wonder if you can reinitialize a new form with the returned form data and the instance as the new object.
form = methodThatGetsForm(somearg)
new_form = ExampleModelForm(form.cleaned_data, instance=ExampleModel.objects.get(pk=getID(somearg)))
new_form.save()
If not, there should be a way to get the data as a dictionary of key/value pairs for the fields from the form
returned, using it's ._meta
data. I think if you send that dictionary to the form init it will assign those values to the instance object, just like sending it request.POST
.
Upvotes: 2