防止多次提交表单-django [英] prevent a form to be submitted multiple times - django
问题描述
我正在提交表格.在那之后,我正在做 HttpResponseRedirect
,这样,如果我刷新页面,就不会提交表单.但是,如果我在浏览器中返回
并再次提交表单,该表单将被保存多次.我该如何预防呢?
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?
推荐答案
一种方法是对表单字段进行哈希处理,当服务器收到请求时,您检查表单哈希是否已经存在(例如,表单已经存在)提交).像这样:
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
其中hashed_form是连接的表单数据,或者是您喜欢的表单数据
where hashed_form is the form data concatenated or in anyway you like
因此,不会提交任何被认为相等的两种形式
thus, no two forms considered equal will ever be submitted
这篇关于防止多次提交表单-django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!