How does a template in django get a user object?
Using the django.contrib.auth.context_processors.auth
context processor, you can access the instance auth.User
in your template.
If
TEMPLATE_CONTEXT_PROCESSORS
contains this processor, eachRequestContext
will contain these variables:
user
- an instanceauth.User
representing the current user on the system (or an AnonymousUser instance if the client is not registered).
Just define django.contrib.auth.context_processors.auth
in settings TEMPLATE_CONTEXT_PROCESSORS
and then use {{user}}
in your template.
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth", # define this in your settings
....
)
Template context processors:
Its set of attributes is used to populate the context in the RequestContext. These callers take a request object as their argument and return a dictionary of items to be merged into the context.
By default, the following Django 1.6 installs the following context processors:
("django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages")
What variables are there in the template?
You can find out which all the variables are present in the whole template by using parameters TEMPLATE_CONTEXT_PROCESSORS
. Each context handler defined in it includes some variables in the context. For example, django.contrib.auth.context_processors.auth
includes a variable user
containing an object user
, includes a variable in a template. django.core.context_processors.media
MEDIA_URL
To check if all variables are available in a template using different context processors, refer to this Django documentation.
Accessing an object request
in context
You can add django.core.context_processors.request
in TEMPLATE_CONTEXT_PROCESSORS
to settings.py
and access the object request
in your context.
You can also access the current user as {{ request.user }}
. You will need to explicitly add this parameter as it is not present by default.
Add .request
context processor TEMPLATE_CONTEXT_PROCESSORS
to your settings.
TEMPLATE_CONTEXT_PROCESSORS = ( .... `django.core.context_processors.request`, )
EDIT: (Thanks @Ozgur )
Also, add AUTHENTICATION_MIDDLEWARE
in the settings MIDDLEWARE_CLASSES
for the attribute user
to be set on the object.It request
was removed from the default settings MIDDLEWARE_CLASSES
in Django 1.7.
class AuthenticationMiddleware
Adds an attributeuser
representing the currently logged in user to each incoming objectHttpRequest
.
MIDDLEWARE_CLASSES = (
...
# explicitly add the 'AuthenticationMiddleware' class
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
source to share