Django authentication and Ajax - URLs that require login

前端 未结 5 1381
暗喜
暗喜 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:36

    I am facing the same issue, and, like you, I would like a simple decorator to wrap around a Django ajax view in order to handle authentication in the same way that I have other views. One approach that seems promising to me is to use such a decorator in conjunction with JavaScript that looks for a certain value in the response.

    Here is first revised draft of the decorator:

    from functools import wraps
    
    def ajax_login_required(view_func):
        @wraps(view_func)
        def wrapper(request, *args, **kwargs):
            if request.user.is_authenticated():
                return view_func(request, *args, **kwargs)
            json = simplejson.dumps({ 'not_authenticated': True })
            return HttpResponse(json, mimetype='application/json')
        return wrapper
    

    Here is the view:

    @ajax_login_required
    def ajax_update_module(request, module_slug, action):
        # Etc ...
        return HttpResponse(json, mimetype='application/json')
    

    And here is the JavaScript (jQuery):

    $.post('/restricted-url/', data, function(json) {
        if (json.not_authenticated) {
            alert('Not authorized.');  // Or something in a message DIV
            return;
        }
        // Etc ...
    });
    

    EDIT: I've attempted to use functools.wraps, as suggested. I have not actually used this decorator in working code, so beware of possible bugs.

提交回复
热议问题