18👍
✅
That’s a pretty good attempt. Here’s a couple of problems I spotted:
- Your
_decorator
function should return_wrapped_view
. - The indentation for your
if function is None
block is a bit off — thelogin_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)
Source:stackexchange.com