sergiuz
sergiuz

Reputation: 5529

Get request object in class-based View

I want to get the current logged in user in a class-based view. I can do that by extracting the user from the request object, but how can I obtain that object?

class HomeView(TemplateView):
    template_name='home.html'

    def get_context_data(self, **kwargs):
        context = super(HomeView, self).get_context_data(**kwargs)  
        context['username'] =  request.user.username
        return context

Upvotes: 11

Views: 7083

Answers (2)

jack
jack

Reputation: 51

Access self.request.user as follows:

context['username'] = self.request.user

Upvotes: 1

user1593705
user1593705

Reputation:

You can access to it from self.request.user

for example you can do this in your CBV

if self.request.user.is_authenticated():
   ...

or

context['username'] = self.request.user.username
   ...

and so on

Upvotes: 22

Related Questions