Menu Close

How to update an object from edit form in Python Django?

To update an object from edit form in Python Django, we can call save in our view.

For instance, we write

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel

in forms.py to create a form.

And then in views.py, we write

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}) 

to create the MyForm instance with request.POST and the MyModel object we want to by the id.

And we call form.save to save the form is the form‘s values are valid as returned by is_valid.

Otherwise, we render the form in the template.

Posted in Python, Python Answers