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?
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With