prevent a form to be submitted multiple times - django

余生长醉 提交于 2019-12-12 01:33:19

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/23326873/prevent-a-form-to-be-submitted-multiple-times-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!