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 user. Please follow this link to see which middleware that I use.
I call this middleware with:
get_current_user()
This worked fine till now. But now I experienced some strange behaviour and only for one special use-case.
I'm using this get_current_user() in a custom manager to return only projects for which the currently logged in user is a member. Membership is defined through the model "ProjectMembership". This model looks like this:
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)
In the project model I have set a custom manager called user_objects. The project model looks like this (simplified):
class Project(models.Model):
name = models.CharField(max_length=100)
#Managers
objects = models.Manager()
user_objects=UserProjectManager()
The UserProjectManager() is now my point of concern. The manager looks like this:
class UserProjectManager(models.Manager):
def get_query_set(self):
print "current user is" + str(get_current_user())
return super(UserProjectManager, self).get_query_set().filter(projectmembership__member=get_current_user())
I added print "current user is" + str(get_current_user())
in order to debug it.
This print statement always! prints out the currently logged in user. When I created this function the server (manage.py runserver) was running and I did not restarted the server and the method runs as I would have expected.
But if I restart the server with manage.py runserver the UserProjectManager() crashes with this error:
caught an exception while rendering: Incorrect integer value: 'AnonymousUser' for column 'member_id' at row 1
I uploaded the error page: link
Interestingly enough is that when I let the server running (after the error was thrown) and then change something in my source-code (add a sign and remove it) and save it (somewhere in my project, it does not matter where!!), click again on the link that has thrown the error, it works! More interesting is that the
print "current user is" + str(get_current_user())
in front of the line that throws the error, always returns the logged-in user correctly!
This does not make a lot of sense to me. Especially since it works if I just resave ( which leads to an automatic restart of the server!) my source.
I'm 100% sure that the error is created in the above outlined source line, since I changed this:
return super(UserProjectManager, self).get_query_set().filter(projectmembership__member=get_current_user())
to this:
return super(UserProjectManager, self).get_query_set())
and then it works perfectly fine. I just say this since the above posted error is maybe a bid misleading.
Probably tough to help me out here. Would appreciate any help!
Edit:
The first answer below from "whrde" stated that the middleware approach is probably a bad idea, whereas the people in the other thread link said that the approach is fine.
Therefore I wanted to state another example where such a middleware is really convenient to use. I use it all over my application. I would just be interested if I really should remove this middleware from my app. since probably I will get more errors than the one that I posted or that the approach is fine. For example overwriting the save method for a model and setting the current_user is really easy in using this middleware. It saves me to write the same three lines in each view afer save().
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)
created_by = models.ForeignKey(User, editable=False, related_name='project_membership_creator')
created = models.DateTimeField(auto_now_add=True, editable=False, verbose_name='creation date')
modified_by = models.ForeignKey(User, editable=False, related_name='project_membership_modifier')
modified = models.DateTimeField(auto_now=True, editable=False)
#Managers
objects = models.Manager()
user_objects=UserProjectMembershipManager()
class Meta:
unique_together = (("project", "member"),)
def __unicode__(self):
return u'%s in project: %s' % (self.member, self.project)
def save(self):
if not self.id:
self.created_by = get_current_user()
self.modified_by = get_current_user()
super(ProjectMembership, self).save()
Edit: Conclusio: Do not use the get_current_user() middleware since there is absolutely no need to use it. Pass the request object to your forms, object managers, overwritten object save methods etc.. and everything will be fine ;-)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With