37

I have created a ModelForm class to be able to create and edit database entries. Creating new entries works well, however, i dont know how to use ModelForms to edit/update an existing entry. I can instantiate a ModelForm with a database instance using:

form  = MyModelForm(instance=MyModel.objects.get(pk=some_id))

However, when i pass this to a template and edit a field and then try to save it, i create a new database entry instead of updating "some_id"?

Edit1: This is my view

def editData(request):
if request.method == 'POST':
    form = MyModelForm(request.POST, request.FILES)

    if form.is_valid():
        editedEntry = form.save() # <-- creates new entry, instead of updating
0

2 Answers 2

59

Remember you still need to use the instance parameter when you instantiate on POST.

instance = MyModel.objects.get(whatever)
if request.method == "POST":
    form = MyModelForm(request.POST, instance=instance)
    ...

else:
    form = MyModelForm(instance=instance)
Sign up to request clarification or add additional context in comments.

4 Comments

Ok i was not doing that. So how should i pass my primary key "some_id" to the html template and back again to the view. Should i do it manually as a hidden form field or is there a way to have Django take care of it?
There's no need to do that. Just use the pattern as I show above.
But to do this: instance = MyModel.objects.get(whatever), i need to substitute "whatever" with the primary key "some_id" which i used to create the initial MyModelForm. From where do i get that?
From the same place you got it from originally, ie the URL.
3

Also possible and slightly shorter:

instance = MyModel.objects.get(whatever)
form = MyModelForm(request.POST or None, instance=instance)
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.