I want to restrict access to a particular view so that only AJAX requests are accepted, so I implemented the following decorator:
def require_ajax(func):
def decorator(func):
def inner(request, *args, **kwargs):
if not request.is_ajax():
return HttpResponseBadRequest()
return func(request, *args, **kwargs)
return inner
return decorator
This works perfectly in function views, but I cannot figure out how to use it in class based views. I have tried this but got errors, I assume due the old version of Django I am using.
And well, my class-based view:
class AjaxView(TemplateView):
template_name = '...'
def get_context_data(self, **kwargs):
...
return context
@method_decorator(require_ajax)
def dispatch(self, *args, **kwargs):
return super(AjaxView, self).dispatch(*args, **kwargs)
Implementing the decorator differently solved the issue: