My problem is simple, I have an admin action named "send email":
The problem is, the admin user can call this function twice in a row, probably by clicking "Go" many times; this causes the email to be sent multiple times. Is there a way to prevent it?
I tried to put a timeout in the end of the admin function send_email
but it's not working: it takes 10 seconds between each users, and I have many users.
def send_email(modeladmin, request, queryset):
...
time.sleep(10)
CodePudding user response:
You can use JavaScript to prevent double clicking on the button.
To add javascript to your admin, you can override the admin HTML templates or adding a javascript using this approach
const button = document.querySelector("#my-go-button");
let didIClickGo = false;
button.addEventListener("click", (event) => {
if (!didIClickGo) {
didIClickGo = true;
} else {
event.preventDefault();
}
});
Note: on line 1, point the selector to your button.
Another option would be rate-limiting on the backend where you would save the data about the emails and whenever you call the function, you should check if you sent an email to this user in the last couple seconds maybe.
CodePudding user response:
You can check if the queryset is different from the last time to avoid calling send_email
twice in a row:
old_queryset = None
def send_email(modeladmin, request, queryset):
if self.old_queryset != queryset:
self.old_queryset = queryset
... # Inserts your code here in the "if" block
You must define old_queryset
as a property of the ModelAdmin
subclass.