问题
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.
回答1:
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
.
回答2:
You can access the request in a Class based view at self.request
.
So to get the user you'd use:
self.request.user
来源:https://stackoverflow.com/questions/27072123/access-request-user-in-django-classed-based-generic-view