V
V
vfvnvsyevsky2015-02-21 21:05:48
Django
vfvnvsyevsky, 2015-02-21 21:05:48

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)

How can we simplify this so that the user's data is passed to main.html by default without being explicitly passed to views each time?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2015-02-22
@vfvnvsyevsky

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,
        '...': '...',
    })

Somewhere in views.py:
def view(request):
    context = base_context(request)
    context['this view specific data'] = 'happy coding'
    return render_to_response('template.html', context)

Thus, you:
1. Do not clutter up the general request flow and retain control over the context of any view. Context processors will be called for any render, while this approach will allow you to always have a minimum of necessary data at hand and full control over all views.
2. Pass only what really needs to get into the context of the template engine. Moreover, in individual views you can even override the basic parameters, which is not so convenient to do with context processors. (but better see item 3)
3. You can expand the abstraction as you like, and create at least 2, at least 3, at least more basic contexts for all sorts of situations (depending on the architecture).

Y
Yuri Shikanov, 2015-02-21
@dizballanze

You need to use request context processor

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question