Django: accessing session variables from within a template?

前端 未结 9 1475
陌清茗
陌清茗 2020-11-28 20:23

If I set a session variable in Django, like:

request.session[\"name\"] = \"name\"

Is there a way I can access it from within a template, o

相关标签:
9条回答
  • 2020-11-28 21:18

    You can pass a request variable to a template and there use:

    {{ request.session.name }}
    
    0 讨论(0)
  • 2020-11-28 21:19

    Maybe a bit too late now. If you directly set TEMPLATE_CONTEXT_PROCESSORS in settings.py, you will lose all default TEMPLATE_CONTEXT_PROCESSORS value. Here is what I do in my settings.py:

    from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as DEFAULT_TEMPLATE_CONTEXT_PROCESSORS
    
    TEMPLATE_CONTEXT_PROCESSORS = DEFAULT_TEMPLATE_CONTEXT_PROCESSORS + (
        'django.core.context_processors.request',
    )
    
    0 讨论(0)
  • 2020-11-28 21:22

    I am using Django 1.9 (March 2016) and to get {{ request.session.name}} to work, my settings have this::

    TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]
    

    The difference from the previous answers is: 'django.core.context_processors.request' became 'django.template.context_processors.request'

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