43

After I submit the form for the first time and then refresh the form it gets resubmitted and and I don't want that.

Here's my form in template :

<form action = "" method = "POST"> {% csrf_token %}
    {{ form.as_p }}
    <input type = "submit" value = "Shout!"/>
</form>

How can I fix this ?

Here's my views:

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()
            form = GuestBookForm()
    else:
        form = GuestBookForm()

    return render_to_response('guestbook/index.html', {'shouts' : shouts,
                                             'form' : form },
                              context_instance = RequestContext(request))
Marijus
  • 4,195
  • 15
  • 52
  • 87

6 Answers6

61

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)

Brant
  • 5,721
  • 4
  • 36
  • 39
  • 2
    Spot on, I think. I had a hunch and answered this before OP put the views in. –  Apr 28 '11 at 19:05
  • Ah, I see he added the views while I was posting. I can change this to match. – Brant Apr 28 '11 at 19:09
  • No need to change, I've already got it to work right, thanks ! – Marijus Apr 28 '11 at 19:10
  • 1
    This is exactly what you want to do. It's surprising how many major websites fail to do the redirect-after-successful-submit action. – Peter Rowell Apr 28 '11 at 19:11
  • How to implement the method: `some_form`, I can't see any built-in API. (django 1.9) – Alston Jun 30 '16 at 01:29
  • I tried your solution and got "The view someview didn't return an HttpResponse object. It returned None instead." error, any Idea? – Bheid May 08 '17 at 19:58
6

Try:

return redirect ('url', parameter_if_needed)

instead of

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

In my case it works perfectly.

dKen
  • 3,078
  • 1
  • 28
  • 37
Sergei
  • 93
  • 1
  • 6
3

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.

1

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/htmx.org@1.6.0"></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")
0

Use HttpResponseRedirect

create a new view(lets say thank_you) for successful message to display after form submission and return a template.

After successful form submission do return HttpResponseRedirect("/thank-you/") to the new thank-you view

from django.http import HttpResponseRedirect

def thank_you(request, template_name='thank-you.html'):
    return render_to_response(template_name,locals(),context_instance=RequestContext(request))

and in urls.py

url(r'^thank-you/$','thank_you', name="thank_you")

Multiple form submission happens because when page refreshes that same url hits, which call that same view again and again and hence multiple entries saved in database. To prevent this, we are required to redirect the response to the new url/view, so that next time page refreshes it will hit that new url/view.

0

This solution worked for me. After form submission we have have to display a message in our template in form of popup or text in any form so though HttpResponseRedirect may prevent form resubmission but it won't deliver the message so here is what I did.

from django.contrib import messages

def index_function(request):
     if request.method == "POST":
     form = some_form(request.POST)
     if form.is_valid():
        # do processing
        # save model, etc.
        messages.success(request, 'Form successfully submitted') # Any message you wish
     return HttpResponseRedirect("/url")

Then inside your template, you can show this message. Since this is global parameter you can display it in any HTML template like the following.

{% if messages %}
<div class="alert alert-success alert-dismissible">
  {% for message in messages %}
    <p>{{ message }}</p>
  {% endfor %}
</div>
{% endif %}