Reputation: 535
What is most effective way to prevent multiple POST requests from happening if the user is clicking on the "Send Message" button multiple times.
<!-- message.html -->
<form action="{% url 'send_message' %}" enctype="multipart/form-data" method="POST">
{% csrf_token %}
<input type="text" id="messagename" name="messagename" maxlength="50" required>
<textarea id="messagecopy" name="messagecopy" required></textarea>
<input type="submit" class="btn" value="Send Message">
</form>
And my views.py
def send_message(request):
if request.method == "POST":
campaign = Campaign()
campaign.name = request.POST["messagename"]
campaign_message = request.POST["messagecopy"]
campaign.messagecopy = campaign_message
campaign.save()
send_message(campaign_message)
redirect('home')
Update I added to my html the following script:
function disable_on_click() {
var x = document.getElementsByClassName('btn');
var i;
for (i = 0; i < x.length; i++) {
x[i].setAttribute("disabled", "disabled")
}
}
I updated <input type="submit" class="btn" value="Send Message">
to <input type="submit" onclick="disable_on_click()" class="btn" value="Send Message">
Now button gets disabled on click but POST request doesn't go through at all
Update #2
Something that worked for me was adding an onsubmit <form action="{% url 'send_message' %}" enctype="multipart/form-data" method="POST" onsubmit="myButton.disabled = true; return true;">
and adding myButton as name of button <input name="myButton" type="submit" class="btn" value="Send Message">
Upvotes: 1
Views: 2177
Reputation: 31
What you're probably looking for is called idempotency and it can be solved by generating a key that will be part of the POST request and the created database object and is required to be unique.
ok, the issue of multiple POST requests is not solved with this method but at least the critical action of creating multiple entries in the database.
Upvotes: 3
Reputation: 3527
Best is to stop them with js:
script.js (pure js):
function disable_on_click() {
var element = document.getElementById('the-button-id');
element.setAttribute("disabled", "disabled");
}
script.js (jquery):
$('#the-button-id').click(function() {
$(this).prop('disabled', true);
});
Upvotes: 1