I am currently working on a Django project that involves events where users can join by adding their user_id and event_id to the attend model. On the event page, there is a join button form that, when clicked, adds the user to the attendees list. After clicking the button, it disappears and is replaced by a 'Leave Event' button, and vice versa. This functionality works as intended; however, I have encountered an issue.
The problem arises when a user clicks the button twice in quick succession before it disappears. This results in an error because the system attempts to add or remove an attendee object that already exists or does not exist.
Is there a way to prevent users from clicking the button multiple times, thereby avoiding sending duplicate POST requests? Alternatively, could the onclick function of the button be modified to prevent multiple requests being sent if the user clicks it again before it disappears?
UPDATE: I have resolved the Django part of the issue, whereby errors no longer occur if a user clicks the join or leave button multiple times. However, users can still continuously click the button, causing the page to endlessly reload.
Below is the JavaScript code responsible for displaying the join or leave button when the page loads or when either button is clicked:
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";
}
}
Here are 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>