views:

82

answers:

2

I'd like to output some information that depends on session data in Django. Let's take a "Login" / "Logged in as | Logout" fragment for example. It depends on my request.session['user'].

Of course I can put a user object in the context every time I render a page and then switch on {% if user %}, but that seems to break DRY idea - I would have to add user to every context in every view.

How can I extract a fragment like that and make it more common?

A: 

Are you trying to make certain areas of your site only accessible when logged on? Or certain areas of a particular page?

If you want to block off access to a whole URL you can use the @login_required decorator in your functions in your view to block certain access. Also, you can use includes to keep the common parts of your site that require user login in a separate html that gets included, that way you're only writing your if statements once.

AlbertoPL
+5  A: 

Use template inheritance to derive all of your templates from a common base that suitably uses the common parts of the context, and make all your contexts with a factory function that ensures the insertion in them of those common parts.

Alex Martelli
I was actually expecting some decorator magic for views... But hey - this solution works too :D
viraptor
@viraptor, glad to hear this - I think magic is usually better avoided when something can be accomplished with more focus on simplicity!
Alex Martelli