Categories
Python Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *