开发者

Is it possible automatically include user to all templates?

开发者 https://www.devze.com 2023-03-02 14:30 出处:网络
I have project in Django 1.3. In order to show username in all pages I use such tags in bas开发者_运维百科e.html

I have project in Django 1.3. In order to show username in all pages I use such tags in bas开发者_运维百科e.html

{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}.  
    <a href="/proc/accounts/logout/">loggout</a></p>
{% else %}
    <a href="/proc/accounts/login/">loggin</a>
{% endif %}

But if I dont return context_instance=RequestContext(request) from view value of user in template is empty. The 'django.contrib.auth.context_processors.auth' is included to TEMPLATE_CONTEXT_PROCESSORS.

Is it possible automaticaly include user to all templates?


since django 1.3. use shortcuts.render function and dont warry about requestcontext including to your views


You've given the answer yourself. As long as you use a RequestContext, it will be included in all templates.

If you really find that too much work, you could use the (new in 1.3) TemplateResponse class.


Or simply create a context processor. See http://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors

Put this in context_processor.py

def root_categories(request):
    return {
        'user': request.user,
    }

in settings.py add the context processor.

now in your template try: {{ user }}

0

精彩评论

暂无评论...
验证码 换一张
取 消