1

A button click in my app calls a view which does a few database changes and then redirects to a new views which renders html. When the user typically clicks on the link, he accidentally clicks on in twice to thrice in a couple of seconds. I want to block the view call if the same call was made less than 10 seconds ago. Of course I can do it by checking in the database, but I was hoping to have a faster solution by using some decorator in django.

Pratik Poddar
  • 1,303
  • 2
  • 18
  • 34

3 Answers3

2

You should disable the button with JavaScript after clicking on it.

This way the user is unable to trigger the view multiple times.

Simeon Visser
  • 106,727
  • 18
  • 159
  • 164
2

This should help. It's a JavaScript to disable the button on click, enable it after the operation completes.

$(document).ready(function () {
    $("#btn").on("click", function() {
        $(this).attr("disabled", "disabled");
        doWork(); //this method contains your logic
    });
});

function doWork() {
     alert("doing work");
     //actually this function will do something and when processing is done the button is enabled by removing the 'disabled' attribute
     //I use setTimeout so you can see the button can only be clicked once, and can't be clicked again while work is being done
     setTimeout('$("#btn").removeAttr("disabled")', 1500);
}

More info here.

Community
  • 1
  • 1
Hec
  • 754
  • 1
  • 4
  • 23
1

No, you can't use decorators in Django to do that.

The methods in your views file are supposed to be telling what to show on your screen. Whereas, the template files are created to tell Django how you want to show them.

You want Django to not count two consecutive calls on same view.

The problem is:

  • What do you mean by "consecutive"? How fast should I click to make it "non-consecutive"? What if I write a script that does the clicks? How would you define consecutive then?

  • Even if you did do that above part using some hack, the next problem would be to differentiate between the requests that come from different users (to that view). How would you differentiate between them to determine the "consecutiveness" of a particular user?

Why make unnecessary changes to do all this stuff?

Django is supposed to be used along with other things too. I have learned this the hard way. Using Javascript is the only way to do it, without any problems.

Client-side, one click and poof! disabled. Very fast and you have the request in pool.

Doing this part is easy. Refer to these links for more info:

How to disable html button using JavaScript?

Disable/enable an input with jQuery?

Community
  • 1
  • 1
Bharadwaj Srigiriraju
  • 2,106
  • 4
  • 24
  • 44