Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a library to prevent duplicate form submissions exist for django?

I am trying to find a way to prevent users from double-submitting my forms. I have javascript that disables the submit button, but there is still an occasional user who finds a way to double-submit.

I have a vision of a re-usable library that I could create to protect from this.

In my ideal library, the code block would look something like this:

try:
    with acquire_lock({'field1':'abc', 'field2':'def'}) as lock:
        response = #do some credit card processing
        lock.response = response
except SubmissionWasDuplicate, e:
    response = e.response

The lock table would look something like this:

duplicate_submission_locks

  • submission_hash # a MD5 of the submitted arguments
  • response # pickled data
  • created_at # used for sweeping this table
  • lock_expired # boolean signifying if the lock has expired

Does anyone know if this already exists? It doesn't seem to difficult to write, so if it doesn't exist I may write it myself.

like image 269
Gattster Avatar asked Jan 26 '10 01:01

Gattster


1 Answers

You can use a session to store the hash

import hashlib

def contact(request):
    if request.method == 'POST':
        form = MyForm(request.POST)
        #join all the fields in one string
        hashstring=hashlib.sha1(fieldsstring)
        if request.session.get('sesionform')!=hashstring:
            if form.is_valid() :                                         
                request.session['sesionform'] = hashstring
                #do some stuff...
                return HttpResponseRedirect('/thanks/') # Redirect after POST  
        else
           raise SubmissionWasDuplicate("duplicate")
    else:
        form = MyForm() 

With this approach (not deleting the session cookie) the user can't re-store the data util the session expires, by the way, i'm assuming that exist something who identify the user who send the data

like image 142
Kristian Damian Avatar answered Oct 13 '22 04:10

Kristian Damian