django get_current_user() middleware - strange error message which goes away if source code is “changed” , which leads to an automatic server restart

后端 未结 2 1654
生来不讨喜
生来不讨喜 2021-01-02 19:01

I\'m using a middleware to get the currently logged in user in my views and models. This helps me to for example return only the objects created or assigned to the logged-in

2条回答
  •  旧时难觅i
    2021-01-02 19:39

    Ignoring the thread local sideshow, your problem is probably related to the fact that the AnonymousUser object is not really a User model instance. Querying the database with this object may not get you very far. You will want to check for authenticated users at some point, either in the view:

    if request.user.is_authenticated():
        Project.objects.for_user(request.user)
    

    Or in your manager method:

    def for_user(self, user):
        if user.is_authenticated():
            return self.get_query_set().filter(projectmembership__member=user)
        else:
            return self.get_query_set().none()
    

提交回复
热议问题