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
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)
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()