Ajax required decorator

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
from django.http import HttpResponseBadRequest

def ajax_required(f):
    """
    AJAX request required decorator
    use it in your views:

    @ajax_required
    def my_view(request):
        ....

    """    
    def wrap(request, *args, **kwargs):
            if not request.is_ajax():
                return HttpResponseBadRequest()
            return f(request, *args, **kwargs)
    wrap.__doc__=f.__doc__
    wrap.__name__=f.__name__
    return wrap

More like this

  1. require XMLHttpRequest view decorator by skam 5 years, 4 months ago
  2. A custom 500 handler which is AJAX-aware by mallipeddi 5 years, 4 months ago
  3. Effective content caching for mass-load site using redirect feature by nnseva 1 year, 11 months ago
  4. HttpMethodsMiddleware by hawkeye 6 years, 2 months ago
  5. Simple Exception Response for AJAX debugging by newmaniese 5 years, 3 months ago

Comments

AdamKG (on May 23, 2008):

Might want to check out request.is_ajax(). It does essentially the same thing; it'd just change line 14.

#

kioopi (on May 24, 2008):

Maybe returning a HTTP-Code in the 400 range ('Bad Request') would be more appropiate?

#

jeffsim (on May 29, 2008):

Thanks for the snippet.

I agree that you could replace request.META.get with request.is_ajax() and return a HttpResponseBadRequest instead, however this is still a very useful snippet!

#

zenx (on May 31, 2008):

I've updated the code with your recommendations. Thank you!

#

mike8 (on May 25, 2010):

You have to make a instance of HttpResponseBadRequest.

#

(Forgotten your password?)