Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access current user in Django class based view

Tags:

python

django

I cannot access current logged in user in Django class based view:

models.py:

class Userproject(models.Model):
    class Meta:
        verbose_name = u'pp'
        verbose_name_plural = u'pps'

    user = models.ForeignKey(settings.AUTH_USER_MODEL, 
    related_name="project", verbose_name=_("Владелец проекта"))
    #user = models.ForeignKey(User, unique=True)

    name = models.TextField(u'Название проекта', unique=True)
    date_created = models.DateTimeField(u'Дата создания', 
        default=datetime.now(), db_index=True)
    date_until = models.DateTimeField(u'Оплачен по', default=datetime.now(), db_index=True)

views.py:

@login_required
class UserprojectList(ListView):
    context_object_name = 'userproject_list'
    queryset = Userproject.objects.filter(user=self.request.user)
    template_name = 'userproject_list.html'  

when i navigate to url i see error: name 'self' is not defined

if i change self.request.user to request.user the error is: name 'request' is not defined

Note that without user filtering view is working and shows data django 1.8.5

like image 676
Vic Nicethemer Avatar asked Nov 19 '15 16:11

Vic Nicethemer


1 Answers

@pythad's answer is correct. But on Django 1.9+, instead of the dispatch method, you can use django.contrib.auth.mixins.LoginRequiredMixin to replace the old-style @login_required decorator.

from django.contrib.auth.mixins import LoginRequiredMixin

class UserprojectList(LoginRequiredMixin, ListView):
    context_object_name = 'userproject_list'
    template_name = 'userproject_list.html'

    def get_queryset(self):
        return Userproject.objects.filter(user=self.request.user)
like image 58
Quique Avatar answered Sep 30 '22 00:09

Quique