Grabbing current logged in user with Django class views?

django, python, view

Solution

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

Problem

I'm trying to grab the currently logged in user and display at the the top of every view. I've searched all over the place for this, but I can't ever find a straight answer for my problem. I was able to get it in the form view, but for some reason I can't display it in a normal view. It's driving me nuts. ``` from django.http import HttpResponse, Http404 from django.views.generic import ListView, DetailView, FormView from django.template import RequestContext, loader, Context from django.core.urlresolvers import reverse from boards.models import Links, LinksCreateForm, Category from django.contrib.auth.models import User def get_user(request): current_user = request.get.user return current_user class LinksListView(ListView): model = Links class LinksDetailView(DetailView): model = Links class LinksCreateView(FormView): template_name = 'boards/link_create.html' form_class = LinksCreateForm def form_valid(self, form): name = form.cleaned_data['name'] description = form.cleaned_data['description'] user = self.request.user category = Category.objects.get(id=form.cleaned_data['category'].id) link = Links(name=name, description=description, user=user, category=category) link.save() self.success_url = '/boards/' return super(LinksCreateView, self).form_valid(form) ```

Original source