On Wed, Mar 30, 2011 at 1:11 PM, Tony <tonyl7...@gmail.com> wrote: > Is there a way to use the "request.user" attributes in a custom model > manager? So I could filter by certain attributes the current logged > in user has? This is the preferable way I would like to filter the > objects the user sees, so if there is a way, I would appreciate the > help. If there is no way to do it like this, I would be open to other > suggestions although, the way my project is structured I dont want to > do this in my view functions.
First, you need to understand that doing it in the view function is the right place to do it. There it's easy; you'd just do something like:: def my_view(request): objects = MyModel.objects.viewable_by(request.user) Your question is a bit like asking, "Is there a good way to get more ventilation in this room? I know I could just open a window, but the way the room is structured I'd rather cut holes in the wall or something." That is, avoiding doing view-like things in views is deliberately doing things the hard way. So please, think about doing this right. The guy who has to maintain your code will thank you. That said, if you *must* go about this the wrong way, the typical approach is to combine a piece of middleware (hack alert #1) with threadlocals (hack alert #2). The middleware would look something like:: # myapp/middleware.py import threading evil_threadlocals = threading.local() def get_request(): return evil_threadlocals.request class EvilMiddleware(object): def process_request(self, request): evil_threadlocals.request = request You'd then add ``myapp.EvilMiddleware`` to ``MIDDLEWARE_CLASSES``, and then deep in your manager you'd do:: class MyManager(models.Manager): def evil_hacky_method(self): from myapp.middleware import get_request return self.filter(user=get_request()) Hopefully I've made it clear that doing this is a bad idea, so *please* think about a light refactor before you head down this path. Jacob -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.