문제

I'm fairly new to Django (using 1.6.2) and I fear that I may be getting into poor practices, so I must ask:

Currently I'm handling some simple views: home, profile. For both of these views, I check if a user is logged in with request.user. And if that user is logged in, I pass his info into context{} and send that to the template.

So, do I basically need to do that for every view in which I want to include that information?

#views.py 

def home(request):
....etc....
context = { 
    'players' : players, 
    'teams' : teams, 
}

if request.user.is_authenticated():
    p = Player.objects.get(user=request.user)
    if p:
        context['p'] = p
return render(request, 'home.html', context)

So I basically check if I should ADD that bit of info to the context if it's available before sending it. Problem is, this info is really used as a header, that should be on every page. Is there a way for me to include it on every view without bringing it through context?

Many thanks in advance. You guys here at StackOverflow have truly helped so many of us get started!

도움이 되었습니까?

해결책 2

While ndpu has correctly pointed you to context processors to solve the general problem, there doesn't really seem to be any need in this case.

You already have a direct relationship between the current user and the relevant Player: I assume that is a one-to-one. And the user object is already passed to the template context by the default context processors, as long as you are using RequestContext (which you are, via the render shortcut.) So, without any extra context at all, you can simply do this in your template:

{{ user.player }}

to get the player.

다른 팁

You can write a custom context processor:

def foo(request):
    """ 
    Adds Player to context
    """

    context = {'p': None}
    if request.user.is_authenticated():
        p = Player.objects.get(user=request.user)
        if p:
            context['p'] = p

    return context

and add it to TEMPLATE_CONTEXT_PROCESSORS tuple in settings.py (assumed that foo placed in context_processors.py module in your application folder):

TEMPLATE_CONTEXT_PROCESSORS = (
    # ...
    "your_app_name.context_processors.foo",
)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top