Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access request.user in Django Classed Based Generic View

How can I access request.user inside a Classed Based Generic View?

This is the code:

class TodayView(TemplateView):
    template_name = "times/today.html"
    if Records.objects.all().count() > 0:
        last_record = Records.objects.latest('id')
    else:
        last_record = None
    actual_time = datetime.today()
    activities = Activity.objects.filter(owner=request.user)

    def get_context_data(self, **kwargs):
        context = super(TodayView, self).get_context_data(**kwargs)
        context["today"] = self.actual_time

        return context

Right now, I get the error "request is not defined", if I write "self.request.user", I get "self" is not defined, which is understandable. I can think of a couple of ways to solve this but I want to know if there is a standardized/consensus on how to access request.user on Django Classed Based Generic Views.

like image 986
Alejandro Veintimilla Avatar asked Nov 21 '14 23:11

Alejandro Veintimilla


2 Answers

The problem is that you should not be putting code at class level. All that code after template_name will be executed when the class is defined, not when the view is called. Not only is self and request not defined at that point, but also today() will be fixed at process startup.

All that code belongs inside get_context_data, from where you can do self.request.user.

like image 79
Daniel Roseman Avatar answered Oct 11 '22 19:10

Daniel Roseman


You can access the request in a Class based view at self.request.

So to get the user you'd use:

self.request.user
like image 31
schillingt Avatar answered Oct 11 '22 20:10

schillingt