Django and Middleware which uses request.user is always Anonymous

前端 未结 7 1207
天命终不由人
天命终不由人 2021-01-30 10:37

I\'m trying to make middleware which alters some fields for the user based on subdomain, etc...

The only problem is the request.user always comes in as AnonymousUser wit

7条回答
  •  悲哀的现实
    2021-01-30 11:31

    Based on Daniel Dubovski's very elegant solution above, here's an example of middleware for Django 1.11:

    from django.utils.functional import SimpleLazyObject
    from organization.models import OrganizationMember
    from django.core.exceptions import ObjectDoesNotExist
    
    
    def get_active_member(request):
        try:
            active_member = OrganizationMember.objects.get(user=request.user)
        except (ObjectDoesNotExist, TypeError):
            active_member = None
        return active_member
    
    
    class OrganizationMiddleware(object):
        def __init__(self, get_response):
            self.get_response = get_response
    
    
        def __call__(self, request):
            # Code to be executed for each request before
            # the view (and later middleware) are called.
    
            request.active_member = SimpleLazyObject(lambda: get_active_member(request))
    
            response = self.get_response(request)
    
            # Code to be executed for each request/response after
            # the view is called.
            return response
    

提交回复
热议问题