How to update an object from edit form in Django?
Solution 1:
Why don't you just use ModelForm?
# forms.py
# ...
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
# views.py
# ...
def my_view(request, id):
instance = get_object_or_404(MyModel, id=id)
form = MyForm(request.POST or None, instance=instance)
if form.is_valid():
form.save()
return redirect('next_view')
return render(request, 'my_template.html', {'form': form})
See https://docs.djangoproject.com/en/3.0/topics/forms/modelforms/#the-save-method for more details.
Solution 2:
Update for Django 1.6 and further version
# forms.py
# ...
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
# views.py
def my_view(request, id):
instance = MyModel.objects.get(id=id)
form = MyForm(request.POST or None, instance=instance)
if form.is_valid():
form.save()
return redirect('next_view')
return direct_to_template(request, 'my_template.html', {'form': form})