[Solved]-Grabbing current logged in user with Django class views?

13👍

In your generic view implementation you will need to extend get_context_data

def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
        c = super(ReqListView, self).get_context_data(**kwargs)
        user = self.request.user
        return c

Then it depends on your requirements what you want to do with that.

Extending generic view classes for common get_context_data

10👍

Within your view, you have access to the request (and therefore the user):

self.request.user

Since you are talking about displaying it at the top of a ‘View’, I believe you are wanting access to it in the template.

You should be able to access it in your template as:

{{ request.user }}

6👍

You can add 'django.core.context_processors.request' to TEMPLATE_CONTEXT_PROCESSORS in settings.py and then access current user as {{ request.user }}. If you haven’t this variable, you can add it as:

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.request',
    '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'
)

https://docs.djangoproject.com/en/1.4/ref/settings/#std:setting-TEMPLATE_CONTEXT_PROCESSORS

👤sneawo

0👍

adding to template context processors as @sneawo pointed is the best way to go. however, I prefer not to override defaults, but to extend it. Like this:

from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP
# ...
TEMPLATE_CONTEXT_PROCESSORS = TCP + (
    'django.core.context_processors.request',
)

Why? Because the list of default context processors in django changes from version to version. Some built-in / shipped with (contrib) libraries depend on the default settings. In general, I believe it’s better not to override the defaults unless you have to.

Leave a comment