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

后端 未结 2 1630
生来不讨喜
生来不讨喜 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条回答
  • 2021-01-02 19:34

    This looks like a bad approach: you need to pass the request object around to provide a function/class/method with access to the current user. Don't mess with a global state.

    Create a method on your manager that takes the user as an argument, and call this from your views:

    # models.py
    class ProjectMembership(models.Model):
        project = models.ForeignKey(Project)
        member = models.ForeignKey(User, related_name='project_membership_member_set')
        day_rate = models.PositiveIntegerField(max_length=11)
    
    class ProjectManager(models.Manager):
        def for_user(self, user):
            return self.get_query_set().filter(projectmembership__member=user)
    
    class Project(models.Model):
        name    = models.CharField(max_length=100)
        objects = ProjectManager()
    
    # somewhere deep in views.py
    if request.user.is_authenticated():
        Project.objects.for_user(request.user)
    
    0 讨论(0)
  • 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()
    
    0 讨论(0)
提交回复
热议问题