django form resubmitted upon refresh

Most likely: When you refresh after submitting the form, you are showing the same form page again (without doing anything). You either need to redirect to the record page or a new page after the form has been submitted.

That way, the form becomes empty its data and will not resubmit when you refresh.


My guess is that this is a problem in your view.

After successful submission and processing of a web form, you need to use a return HttpResponseRedirect, even if you are only redirecting to the same view. Otherwise, certain browsers (I'm pretty sure FireFox does this) will end up submitting the form twice.

Here's an example of how to handle this...

def some_view(request):
  if request.method == "POST":
    form = some_form(request.POST)
    if form.is_valid():
      # do processing
      # save model, etc.
      return HttpResponseRedirect("/some/url/")
  return render_to_response("normal/template.html", {"form":form}, context_instance=RequestContext(request))

Given your recently added view above...

def index(request):
    shouts = Shout.objects.all()

    if request.method == "POST":
        form = GuestBookForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            shout = Shout(author = cd['author'], message = cd['message'])
            shout.save()

            # Redirect to THIS view, assuming it lives in 'some app'
            return HttpResponseRedirect(reverse("some_app.views.index"))
    else:
        form = GuestBookForm()

    return render_to_response('guestbook/index.html', {'shouts' : shouts,
                                         'form' : form },
                          context_instance = RequestContext(request))

That will use reverse to redirect to this same view (if thats what you are trying to do)


Try:

return redirect ('url', parameter_if_needed)

instead of

return render (request, 'name.hmtl', context)

In my case it works perfectly.


I have found a way and I think it's going to work for any website. what you have to do is add a Htmx cdn or you can call the javascript library from htmx.org like bootstrap CDN.

add this

 before body tag

<script src="https://unpkg.com/[email protected]"></script>

add this or go to their website htmx.org

then what you have to do is go to your form tag and add this....

hx-post=" then add the path in here, where you want to redirect" something like this..

contact html

<form hx-post="/contact" hx-target="body" method="post">
 </form>

you have to add a target depending on your form type. The above example is a contact form I want that contact form to stay on the same page and target its body like this hx-target="body"

views.py

return render(request, "blog/contact.html")

Tags:

Forms

Django