- Author:
- zenx
- Posted:
- May 23, 2008
- Language:
- Python
- Version:
- .96
- Tags:
- ajax decorator decorators xmlhttprequest ajax-required
- Score:
- 5 (after 7 ratings)
Checks if the request is an AJAX request, if not it returns an HttpResponseNotFound. It looks for the XMLHttpRequest value in the HTTP_X_REQUESTED_WITH header. Major javascript frameworks (jQuery, etc.) send this header in every AJAX request.
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
- Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 8 months, 1 week ago
- Crispy Form by sourabhsinha396 9 months ago
- ReadOnlySelect by mkoistinen 9 months, 1 week ago
- Verify events sent to your webhook endpoints by santos22 10 months, 1 week ago
- Django Language Middleware by agusmakmun 10 months, 3 weeks ago
Comments
Might want to check out request.is_ajax(). It does essentially the same thing; it'd just change line 14.
#
Maybe returning a HTTP-Code in the 400 range ('Bad Request') would be more appropiate?
#
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!
#
I've updated the code with your recommendations. Thank you!
#
You have to make a instance of HttpResponseBadRequest.
#
Please login first before commenting.