Access request.user in Django Classed Based Generic View

早过忘川 提交于 2019-12-23 08:01:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!