Django - Custom decorator to allow only ajax request
from functools import wraps
from django.core.exceptions import PermissionDenied
def require_ajax(view):
@wraps(view)
def _wrapped_view(request, *args, **kwargs):
if request.is_ajax():
return view(request, *args, **kwargs)
else:
raise PermissionDenied()
return _wrapped_view
After a google search I've found this:
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
Didn't tried it, so you have to try it. The essential part is request.is_ajax()
which checks if the request is made through AJAX. Check also the docs for more info on is_ajax()
method.
EDIT
To decorate a view class in django see Decorating the class in the documentation. Basically the decorator function wraps a method of the class. So you can use the django @method_decorator()
to wrap a method in your decorator function (ajax_required
):
@method_decorator(ajax_required)
def method_you_want_to_get_only_AJAX_requests():
......