login_required decorator on ajax views to return 401 instead of 302

前端 未结 1 1145
暗喜
暗喜 2020-12-31 05:53

While writing some views to respond to ajax requests i find it somewhat strange that the login_required decorator always returns a 302 status code for not authenticated user

相关标签:
1条回答
  • 2020-12-31 06:25

    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)
                else:
                    return HttpResponse(status=401)
            return _wrapped_view
    
        if function is None:
            return _decorator
        else:
            return _decorator(function)
    
    0 讨论(0)
提交回复
热议问题