On Saturday 17 June 2006 10:50, Adam Hoscilo wrote:

> I would like to filter entries from a logged in user and give him/her
> the ability to edit them - it would be nice to ensure that scope by
> manager.
> As far as I know Models don't have access to request and session data
> (and I realize it's a MVC/MVT schema violation). Is there any way to
> manage that by custom managers or maybe some other nice way?
> PS django.pl coming soon :)

Personally I think that it's bad to have models access HTTP request 
data, but it's not so bad to enable them to have access to 
authorisation data -- this is a very common business requirement.  If 
you don't do it in the model itself, you'd probably need to do it in 
some 'business rules' layer that wraps model access.

So I store the logged in user in threadlocal storage, using a 
middleware, then access it in my models.

It looks like this:

#### myproject/middleware/threadlocals.py

try:
    from threading import local
except ImportError:
    # Python 2.3 compatibility
    from django.utils._threading_local import local

_thread_locals = local()

def get_current_user():
    return getattr(_thread_locals, 'user', None)

class ThreadLocals(object):
    """Middleware that gets various objects from the
    request object and saves them in thread local storage."""
    def process_request(self, request):
        _thread_locals.user = getattr(request, 'user', None)

#### end


Then put ThreadLocals into your list of installed middleware, and import 
the get_current_user() function from your model code.  I often use this 
in custom managers -- if you set the custom manager as your default 
manager, this has the very nice advantage that it works for related 
objects too.

Luke

-- 
A former CEO: "Some of you think that only half of the Board of 
Directors do all the work and the rest do nothing, actually the reverse 
is true."  (True Quotes From Induhviduals, Scott Adams)

Luke Plant || L.Plant.98 (at) cantab.net || http://lukeplant.me.uk/

--~--~---------~--~----~------------~-------~--~----~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~----------~----~----~----~------~----~------~--~---

Reply via email to