Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Custom decorator to allow only ajax request

Tags:

ajax

django

I have few views in my project which are called only by ajax and I need to put in a check that the views are processed only if the request is ajax. So I thought of writing a decorator. Upon searching for similar type of decorators I hit upon few but couldn't understand anything. I make use of class based views and will use this decorator on get/post methods. I did find few snippets but all were written for function based views which made it more difficult for me to understand as I have never worked upon function based views.

I just need to know what is idea behind decorators and how it works.

like image 434
Rajesh Yogeshwar Avatar asked Dec 08 '15 09:12

Rajesh Yogeshwar


2 Answers

    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
like image 173
Harshil jain Avatar answered Nov 09 '22 18:11

Harshil jain


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():
    ......
like image 5
doru Avatar answered Nov 09 '22 19:11

doru