Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent multiple form submissions in Django

I'm looking for a generic way to prevent multiple form submissions. I found this approach which looks promising. Whereas I do not want to include this snippet in all of my views. Its probably easier to do this with a request processor or a middleware.

Any best practice recommendations?

like image 285
Thomas Kremmel Avatar asked Mar 27 '13 23:03

Thomas Kremmel


People also ask

How do I stop multiple form submissions in Django?

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.

How do you prevent multiple submission of a form explain?

Use unobtrusive javascript to disable the submit event on the form after it has already been submitted. Here is an example using jQuery. EDIT: Fixed issue with submitting a form without clicking the submit button. Thanks, ichiban.


1 Answers

Client side, start with JavaScript. You can never trust the client, but its a start.

i.e.

onclick="this.disabled=true,this.form.submit();

Server side you 'could' insert something into a database i.e. a checksum. If its a records you are insert into a database use model.objects.get_or_create() to force the uniqueness on database level you should use unique_together.

Lastly: HTTPRedirect is best, The the method I use when a user processes a payment is to just issue a HTTPRedirect() to the thank you/conformation page. This way refreshing the form won't resubmit and if they go back and try to submit the form again (without refreshing the form) the Django Cross Site Request Forgery (CSRF) will fail, perfect!

like image 92
Glyn Jackson Avatar answered Oct 12 '22 21:10

Glyn Jackson