Django authentication and Ajax - URLs that require login

前端 未结 5 1420
暗喜
暗喜 2020-11-29 15:45

I want to add some Ajax-niceness to my Django-coded website.

In my Django code, I use the @login_required decorator from django.contrib.auth.deco

5条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 16:38

    Built off of Eric Walker's solution, but for Django 2.0

    # Standard Imports
    import functools
    import django.http
    
    def ajax_login_required(view_func):
        @functools.wraps(view_func)
        def wrapper(request, *args, **kwargs):
            if request.user.is_authenticated:
                return view_func(request, *args, **kwargs)
    
            return django.http.JsonResponse('Unauthorized', status=401, safe=False)
    
        return wrapper
    

提交回复
热议问题