views:

97

answers:

3

Every time I open a page I want to get the currently active project id. This will be done by chacking the subdomain and verifying the currently logged in user can view it.

Once I reach my view I want to be able to do

tasks = Task.objects.filter(project = current_project)

WHere current_project (or CURRENT_PROJECT or current_project ???) has already been setup.

Can anyone explain the pros/cons of the various approaches I have found in the docs and put me on the right track?

  1. Sessions
  2. Middleware
  3. Threading
  4. builtins

This was how I did it in the end:

Decorator:

def check4project(fn):

    current_project = 'fred'
    def check(*args, **kw):
        kw['project']=current_project
        return fn(*args, **kw)
    return check

View example

@login_required
@check4project
@tweetpost
def index(request, project=0):

    print project
A: 

Have you considered a custom template tag?

cpharmston
Mostly I want this in the view before calling the template but thanks for the contribution.
+3  A: 

It all depends on what your semantics of "current project" are. Here are some possibilities:

  1. It could be a characteristic of the user: he visits his profile page and sets a current project. This would be stored in the database, and you would access it with the ORM.

  2. It could be a characteristic of the URL, based solely on subdomain. This could be done with middleware, which has access to the request, and could for example, parse the host name and set a custom attribute on the request that you could access in your view functions.

  3. Similar to #2, you could use a view decorator if checking projects is done for some views but not all. This is similar to Django's decorators for checking authorization.

  4. It could be a characteristic of the user's visit to the site: he visits a page of projects, chooses one to work on, and it's sticky until he chooses another project. This would be best stored in the session, which is specifically for this sort of transient storage.

From your description, it sounsd like #2 or #3 is the best for you, depending on how your views divide up between caring about subprojects and not.

Ned Batchelder
Thanks for your helpful answer, it has helped clarify the various options for me.I like the sound of 3. because it's an easy way of validating the user has access to the project at the same time and most but no all views need to be aware of project.
+1 for a view decorator.
Daniel Roseman
+1  A: 

You could make a context_processor and then get your value from the request object.

skyl
a context_processor would not be the best solution for this problem, but it solves another one I was having! Thanks.