Django, request.user is always Anonymous User

后端 未结 9 2085
无人共我
无人共我 2020-12-01 14:57

I am using a custom authentication backend for Django (which runs off couchdb). I have a custom user model.

As part of the login, I am doing a request.user = u

9条回答
  •  温柔的废话
    2020-12-01 15:14

    I too have custom authentication backend and always got AnonymousUser after successful authentication and login. I had the get_user method in my backend. What I was missing was that get_user must get the user by pk only, not by email or whatever your credentials in authenticate are:

    class AccountAuthBackend(object):
    
    @staticmethod
    def authenticate(email=None, password=None):
        try:
            user = User.objects.get(email=email)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            return None
    
    @staticmethod
    def get_user(id_):
        try:
            return User.objects.get(pk=id_) # <-- tried to get by email here
        except User.DoesNotExist:
            return None
    

    Its easy to miss this line in the docs:

    The get_user method takes a user_id – which could be a username, database ID or whatever, but has to be the primary key of your User object – and returns a User object.

    It so happened that email is not primary key in my schema. Hope this saves somebody some time.

提交回复
热议问题