How to check if a user is logged in (how to properly use user.is_authenticated)?

后端 未结 6 1860
挽巷
挽巷 2020-11-28 01:17

I am looking over this website but just can\'t seem to figure out how to do this as it\'s not working. I need to check if the current site user is logged in (authenticated),

6条回答
  •  孤街浪徒
    2020-11-28 01:59

    Django 1.10+

    Use an attribute, not a method:

    if request.user.is_authenticated: # <-  no parentheses any more!
        # do something if the user is authenticated
    

    The use of the method of the same name is deprecated in Django 2.0, and is no longer mentioned in the Django documentation.


    Note that for Django 1.10 and 1.11, the value of the property is a CallableBool and not a boolean, which can cause some strange bugs. For example, I had a view that returned JSON

    return HttpResponse(json.dumps({
        "is_authenticated": request.user.is_authenticated()
    }), content_type='application/json') 
    

    that after updated to the property request.user.is_authenticated was throwing the exception TypeError: Object of type 'CallableBool' is not JSON serializable. The solution was to use JsonResponse, which could handle the CallableBool object properly when serializing:

    return JsonResponse({
        "is_authenticated": request.user.is_authenticated
    })
    

提交回复
热议问题