[Fixed]-Edit view saving twice

1👍

When you look at the save method it clearly shows there isn’t an sql command being executed when commit = False. The actual database call happens in your next line when you do instance.save

If you are seeing two updates happening, it can possibly be because the form is being submitted twice. This can safely be ignored because many RDBMS are smart enough not to update unchanged data. However even that can be avoided by using the standard django pattern of redirect after form handling

instance = edit_form.save(commit=False)
instance.save(update_fields=['content'])
return HttpResponseRediret('/success_url/')
👤e4c5

0👍

You need to specify request.method in the view, if not the form is submitted in the get request also.
Since, the form already contains the “post” instance, form is already valid and it is saved.

Edit your view like this,

def edit(request, id):
    post = get_object_or_404(Post, id=id)
    #If it is a POST request do the thing below.
    if request.method == "POST":
        edit_form = EditPostForm(request.POST or None, instance=post)
        if edit_form.is_valid():
            form.instance.save(update_fields=['content'])
            return HttpResponseRedirect('/')
    else:
        edit_form = EditPostForm(instance=post)
    context = {
            'edit_form': edit_form,
            'form_post': post
            }
    return render(request, 'edit.html', context)

Leave a comment