Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grabbing current logged in user with Django class views?

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)
like image 980
John Smith Avatar asked Jan 20 '13 07:01

John Smith


2 Answers

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

like image 141
Pratik Mandrekar Avatar answered Oct 07 '22 03:10

Pratik Mandrekar


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 }}
like image 10
Matthew Schinckel Avatar answered Oct 07 '22 01:10

Matthew Schinckel