Always including the user in the django template context

前端 未结 8 625
一向
一向 2020-12-04 14:22

I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter

相关标签:
8条回答
  • 2020-12-04 15:21

    its possible by default, by doing the following steps, ensure you have added the context 'django.contrib.auth.context_processors.auth' in your settings. By default its added in settings.py, so its looks like this

    TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.request',
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.auth',)
    

    And you can access user object like this,

    {% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
    {% else %}
        <p>Welcome, new user. Please log in.</p>
    {% endif %}
    

    For more information, refer here http://docs.djangoproject.com/en/1.2/topics/auth/#authentication-data-in-templates

    0 讨论(0)
  • 2020-12-04 15:28

    The hints are in every answer, but once again, from "scratch", for newbies:

    authentication data is in templates (almost) by default -- with a small trick:

    in views.py:

    from django.template import RequestContext
    ...
    def index(request):
        return render_to_response('index.html', 
                                  {'var': 'value'},
                                  context_instance=RequestContext(request))
    

    in index.html:

    ...
    Hi, {{ user.username }}
    var: {{ value }}
    ... 
    

    From here: https://docs.djangoproject.com/en/1.4/topics/auth/#authentication-data-in-templates

    This template context variable is not available if a RequestContext is not being used.

    0 讨论(0)
提交回复
热议问题