I'm working in a Django project which has events that can be joined by users (adding the user_id and event_id to a model attend), In my event I have a join button form that when clicked adds the attend, after clicking the button disappears and appears a new button called leave event and the opposite. All this works, when the user joins or leaves the event page reloads.
The problem I'm having is that I'm able to click the button 2 times in a row before the button disappears getting an error because it is trying to add an attend object that already exists or delete an object that does not exist.
So my question is if there is a way to avoid the user clicking two times the button so it is not sending a POST request 2 times, or at least if he clicks it again before it disappears not sending a request, or there could be a way to apply the button onclick function before sending the POST request?
EDIT: I solved the Django part so I'm not getting an error if the user clicks 2 times the join or leave button, but now the user can still keep clicking the button and the page will keep reloading till he/she stops clicking that same button which I think it is not good.
Here the javascript to show the join or leave button which is executed when the page is loaded or either button is clicked (I first looked in the list of attendants if the logged user is attending, because I didn't find a way to query the attend model in a Django template):
script type="text/javascript">
window.onload = function() {
showJoinLeave();
};
function showJoinLeave() {
var attendants = document.getElementsByClassName("attendant-username");
var username = "{{ user.username }}";
var joinButton = document.getElementById("event-info-join");
var leaveButton = document.getElementById("event-info-leave");
var is_attending = false;
var attendant;
for (attendant of attendants) {
var attendant_name = attendant.innerHTML;
if (attendant_name == username) {
is_attending = true;
}
}
if (is_attending===true){
joinButton.style.display = "none";
leaveButton.style.display = "flex";
}
else {
joinButton.style.display = "flex";
leaveButton.style.display = "none";
}
}
My two buttons:
<form action="{% url 'event-join' object.id %}" method="POST">
{% csrf_token %}
<button type="submit" id="event-info-join" class="icon" title="Join Event" onclick="showJoinLeave()">
<i class="material-icons" title="Join Event">add</i>Join Event
</button>
</form>
<form action="{% url 'event-leave' object.id %}" method="POST">
{% csrf_token %}
<button type="submit" id="event-info-leave" class="icon" title="Leave Event" onclick="showJoinLeave()">
<i class="material-icons" title="Leave Event">add</i>Leave Event
</button>
</form>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…