Simply adds an attribute is_ajax
to a request object, indicating if the request was made via Ajax. Allows you to reuse a lot of POST processing view code to which you'd like to progressively add Ajax:
if request.is_ajax: return JsonResponse(some_json)
else: return render_to_response('some_template.html')
1 2 3 4 5 | class AjaxCheckMiddleware(object):
def process_request(self, request):
is_ajax = request.META.get('HTTP_X_REQUESTED_WITH', None) == 'XMLHttpRequest'
setattr(request, 'is_ajax', is_ajax)
return None
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Nice. I'm just now working on something that I wanted to use the idea of "progressive enhancement" and went about this a slightly different way. But this is nice.
Is the "HTTP_X_REQUESTED_WITH" header common in all browsers?
#
Sorry, I suppose the header would have to be common in the Javascript library you use since it would be sending headers. Thanks.
#
I figured out that you can just use request,is_ajax in the template without using any middleware:
{% if request.is_ajax == True %} ajax specific html. {% endif %}
#
Please login first before commenting.