[Fixed]-Login_required decorator on ajax views to return 401 instead of 302


That’s a pretty good attempt. Here’s a couple of problems I spotted:

  1. Your _decorator function should return _wrapped_view.
  2. The indentation for your if function is None block is a bit off — the login_required_ajax function needs to return the decorated function.

Here’s the decorator with those changes made:

def login_required_ajax(function=None,redirect_field_name=None):
    Just make sure the user is authenticated to access a certain ajax view

    Otherwise return a HttpResponse 401 - authentication required
    instead of the 302 redirect of the original Django decorator
    def _decorator(view_func):
        def _wrapped_view(request, *args, **kwargs):
            if request.user.is_authenticated():
                return view_func(request, *args, **kwargs)
                return HttpResponse(status=401)
        return _wrapped_view

    if function is None:
        return _decorator
        return _decorator(function)

Leave a comment