I have some code that gets the current logged in user.
userID = request.session.get("_auth_user_id")
if userID:
loggedin_user = User.objects.get(pk=int(userID))
else:
loggedin_user = None
I want the username to show up on every page.
At the moment I am putting the code in every view and passing the user object to every template
return render_to_response('index.html', {loggedin_user})
This seems to go against django’s D.R.Y ethic. How can I do this with repeating myself?
EDIT: Maybe User was a bad example.
What if I wanted to get a list of objects from the database,
items = Item.objects.all()
and list them on everypage.
Do I have to write that code and pass the list to the template in every view. Or can I write some code once that will make that list available to all templates?
You should use a custom template tag for something like that. You can fetch the data you need in the custom tag, and send it to the template. All you need to remember is to load the tag up in the template file you’re going to use it in.