mogoli
mogoli

Reputation: 2375

Form resubmits data django

I have a view function that resubmits data when I refresh the page.

def home(request):
    if request.method == 'POST':
        form = ListForm(request.POST or None)

        if form.is_valid():
            form.save()
            all_items = List.objects.all
            messages.success(request,('Item has been added to List'))
            return render(request, 'home.html', {'all_items': all_items})

    else:
        all_items = List.objects.all
    return render(request, 'home.html',{'all_items':all_items})

Any ideas on how to prevent this please. render_to_response is now deprecated from what Ive read.

Thank you

Upvotes: 0

Views: 52

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

Preventing form resubmission is nothing new, the canonical solution is the post-redirect-get pattern: after a successful post, you return a redirect HTTP response, forcing the user's browser to do a get. The canonical Django "form handler" view (in it's function version) is:

def yourview(request):
    if request.method == "POST":
        form = YourForm(request.POST)
        if form.is_valid():
            do_something_with_the_form_data_here()
            return redirect("your_view_name")
        # if the form isn't valid we want to redisplay it with
        # the validation errors, so we just let the execution
        # flow continue...

   else:
       form = YourForm()

   # here `form` will be either an unbound form (if it's a GET
   # request) or a bound form with validation errors.
   return render(request, "yourtemplate.html", {'form': form, ...})

Upvotes: 1

Related Questions