Django: login_required on ajax call

前端 未结 3 1312
花落未央
花落未央 2021-02-20 09:47

I am trying to authenticate user on ajax post but doesn\'t work. Here what I have done

settings.py

LOGIN_URL = \'/accounts/login/\'
LOGI         


        
3条回答
  •  有刺的猬
    2021-02-20 10:15

    Instead of :

    if not request.user.is_authenticated():
       return HttpResponseRedirect('/accounts/login')
    

    return json response :

    if request.user.is_authenticated():
        ## write your code...
        jsonr = json.dumps({ 'authenticated': True })
        return HttpResponse(jsonr, mimetype='application/json')
    else:
        jsonr = json.dumps({ 'authenticated': False })
        return HttpResponse(jsonr, mimetype='application/json')
    

    And At your ajax success response , if not authenticated then redirect to login using windows.location .

    OR you can write decorator : Django authentication and Ajax - URLs that require login

提交回复
热议问题