Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django options for making variables widely available

Tags:

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
like image 883
PhoebeB Avatar asked Sep 13 '09 10:09

PhoebeB


1 Answers

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.

like image 113
Ned Batchelder Avatar answered Oct 01 '22 01:10

Ned Batchelder