Answer the question
In order to leave comments, you need to log in
How to pass data from model to template in Django, bypassing views?
Let's say:
There is a main.html and there is a top navigation bar (which is used with all the inheriting main.html templates) where the name of the logged in user is displayed.
And there is article.html that inherits main.html.
def article renders and passes variables to article.html
And in order for the username to appear in main.html, it must be passed each time through def article:
def article:
user = request.user.username
return render_to_response('article.html', user)
Answer the question
In order to leave comments, you need to log in
For starters: https://www.python.org/dev/peps/pep-0020/
One of the points there is "explicit is better than implicit".
Views in django are designed to pass data and do it explicitly, but how you do it is entirely up to you. You are right, it makes no sense to fence the garden in all views with the transfer of the same data, especially if they are common to most templates, but neither the custom context processor, nor even the custom template tag will help you out as much as one simple construction can :
somewhere in utils.py
def base_context(request):
return Context({
'user': request.user,
'...': '...',
})
def view(request):
context = base_context(request)
context['this view specific data'] = 'happy coding'
return render_to_response('template.html', context)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question