Double submit means that the same request will be sent multiple times. If the processing performed when a POST request is received is executed multiple times, unexpected processing may be performed. It can also be caused by the reload button of the browser, so it is desirable to take some measures.
Countermeasures for double submission of Saikyo
I searched patiently, but it didn't seem to be so, so I made it myself easily. It is a double submit judgment on the server side, not on the client side such as button deactivation.
def set_submit_token(request):
submit_token = str(uuid.uuid4())
request.session['submit_token'] = submit_token
return submit_token
def exists_submit_token(request):
token_in_request = request.POST.get('submit_token')
token_in_session = request.session.POP('submit_token', '')
if not token_in_request:
return False
if not token_in_session:
return False
return token_in_request == token_in_session
In the sample, the flow is as follows.
In exists_submit_token (), submit_token used once is discarded from the session by pop, so if the same request is sent multiple times, error.html will be returned.
views.py
def index(request):
submit_token = set_submit_token(request)
return render(request, 'todo/index.html', {"submit_token": submit_token})
def post(request):
if not exists_submit_token(request):
return render(request, 'todo/error.html', {})
else:
return render(request, 'todo/complete.html', {})
index.html
<form action="{% url 'todo:post' %}" method="post">
{% csrf_token %}
{{ submit_token }}
<input type="hidden" name="submit_token" value="{{ submit_token }}" />
<input type="submit" value="Submit" />
</form>
I would like to use a simpler and easier-to-understand method, but I once compromised with the above implementation. Also, like SessionToken in Struts2, I would like to be able to say that the exact same screen will be returned even after the second and subsequent times of the same request, although it will not be processed. If you have a good library or something you should do, please let us know in the comments.
Recommended Posts