0

I am submitting a form. After that i am doing HttpResponseRedirect so that the form wont be submitted if one i refresh the page. BUT, if i go back in browser and submit the form again, the form will be saved multiple times. How can i prevent this?

I thought of session, meaning i set a session name like this:

if request.session.get('saved', False):
    return HttpResponseRedirect('/already_saved/')    
entry.save() # <-- pseudo save
request.session['saved'] = True

but this causes that the user can never send another form in my page in his actual session.

how can I create unique sessions for each form, so that one form doesnot get submitted multiple times but it is still possible to submit another forms?

doniyor
  • 36,596
  • 57
  • 175
  • 260
  • You can add an expires header to the page with a time in the past (-1) and the page will not be valid when using the back button. Using a session cookie to store it will work too. – shaunl Apr 27 '14 at 17:55
  • take a look here: http://stackoverflow.com/questions/5823580/django-form-resubmitted-upon-refresh – Patrick Bassut Apr 27 '14 at 17:58
  • @PatrickBassut i dont have problems on refresh, i have problems with go back button. but thanks anyway – doniyor Apr 27 '14 at 18:03
  • Do you want the user to not submit the same data twice, or to not submit the same data in a given short time? – Patrick Bassut Apr 27 '14 at 18:06
  • @PatrickBassut not to submit the same form again - no matter in short time or how many times.. – doniyor Apr 27 '14 at 18:28

1 Answers1

2

An approach would be making a hash of the form's field and when the server receives the request you check if the hash of the form is already there (e.g. form already submitted). Something like this:

import hashlib
from django.shortcuts import Http404
sha512 = hashlib.sha512()
sha512.update(form_fields_stringfied)

if not request.session['forbidden_data']:
    request.session['forbidden_data'] = []

hashed_form = sha512.hexdigest()
if hashed_form not in request.session['forbidden_data']:
    request.session['forbidden_data'].append(hashed_form)
else:
    raise Http404

where hashed_form is the form data concatenated or in anyway you like

thus, no two forms considered equal will ever be submitted

Patrick Bassut
  • 3,310
  • 5
  • 31
  • 54