Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: using ModelForm to edit existing database entry

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 
like image 484
WesDec Avatar asked Sep 08 '11 14:09

WesDec


2 Answers

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) 
like image 199
Daniel Roseman Avatar answered Oct 23 '22 20:10

Daniel Roseman


Also possible and slightly shorter:

instance = MyModel.objects.get(whatever) form = MyModelForm(request.POST or None, instance=instance) ... 
like image 43
Davy Avatar answered Oct 23 '22 19:10

Davy