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
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)
Also possible and slightly shorter:
instance = MyModel.objects.get(whatever) form = MyModelForm(request.POST or None, instance=instance) ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With