在Django Classed Based Generic View中访问request.user [英] Access request.user in Django Classed Based Generic View

查看:116
本文介绍了在Django Classed Based Generic View中访问request.user的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何访问基于分类的通用视图中的request.user?

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

现在,我得到错误request is not defined,如果我写self.request.user,我得到self没有定义,这是可以理解的。我可以想到几种方法来解决这个问题,但我想知道是否有关于如何访问基于Django Classed Generic Views的request.user的标准化/共识。

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.

推荐答案

问题是,您不应该将代码放在课堂级别。所有代码 template_name 之后的代码将在定义类时执行,而不是在调用视图时执行。不仅是 self 和请求此时未定义,而且 today()将在进程启动时被修复。

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.

所有代码都属于 get_context_data 你可以做 self.request.user

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

这篇关于在Django Classed Based Generic View中访问request.user的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆