请问 django 视图类中如何获取 request

2015-09-03 06:59:00 +08:00
 artlearn

在视图函数中直接可以将 request 作为参数很简单。
但在视图类中怎么获取呢?

class BaseMixin (object ):
    def get_context_data (self,*args,**kwargs ):
        context = super (BaseMixin,self ).get_context_data (*args,**kwargs )
        try:
            #热门文章
            context['hot_post_list'] = Article.objects.order_by ("-views")[0:10]
            #导航条
            context['nav_list'] =  Category.objects.filter (status=1 )
            #最新文章
            context['latest_post_list'] = Article.objects.order_by ("-create_time")[0:10]
            #用户发布文章数
            #if request.user.is_authenticated ():#验证登录,这里需要 request ,提示没有 request 模块,不知道用什么方式获取 request
                #context['pushed_count'] =  Pushed.objects.filter (user_id=request.user.id ).count ()#要获取登录用户 ID
        except Exception as e:
            logger.error (u'加载通用信息出错'+''.join (e ))

        return context

知道的直接告诉我代码吧,别让我看文档了,我要是有那个心思去看文档早不提问了。

4888 次点击
所在节点    Django
18 条回复
guoqiao
2015-09-03 07:21:10 +08:00
哈哈, 又见理直气壮的拿来主义.
aggron
2015-09-03 07:35:00 +08:00
用 self.request
在 class based views 中是这样的
class FooView (BaseMixin, View ):
虽然 BaseMixin 对象没有 request 属性,但 View 对象有,所有就可以使用,这算很常见的 Mixin 模式(多继承),你可以看看 Python MRO 的知识
hpeng
2015-09-03 07:48:06 +08:00
滚,希望您将我拉黑,别让我去 block 您了,有那心思我就不回复您了
artlearn
2015-09-03 08:22:13 +08:00
谢谢回答
roychan
2015-09-03 08:38:34 +08:00
「我根本不是搞程序的,请原谅我的问题很白痴,能答就答不能答你就闪。大路朝天各走各边,你走你阳关道,我过我的独木桥。我只需要那些好心人回答,根本没把你放在眼里,所以你也不需要把我放在眼里,回滚第一句。别给我装逼拿来主义,除非你这辈子没用过开源。你很屌就不要混社区。回滚第一句。」
sorcerer
2015-09-03 10:20:58 +08:00
楼主这签名,没人会回答你的
jakes
2015-09-03 10:38:57 +08:00
真他喵理直气壮
KIDJourney
2015-09-03 12:52:16 +08:00
不可以举报吗。。。
aisk
2015-09-03 13:43:05 +08:00
为社区做点好事,千万别回答楼主。
为社区做点好事,千万别回答楼主。
为社区做点好事,千万别回答楼主。
aisk
2015-09-03 13:44:28 +08:00
aisk
2015-09-03 13:44:36 +08:00
BGLL
2015-09-03 14:55:25 +08:00
楼主简介太 66666 了:

“我根本不是搞程序的,请原谅我的问题很白痴,能答就答不能答你就闪。大路朝天各走各边,你走你阳关道,我过我的独木桥。我只需要那些好心人回答,根本没把你放在眼里,所以你也不需要把我放在眼里,回滚第一句。别给我装逼拿来主义,除非你这辈子没用过开源。你很屌就不要混社区。回滚第一句。”
zhuangzhuang1988
2015-09-03 14:58:59 +08:00
很简单啊, 给点钱就好了.
artlearn
2015-09-03 15:33:20 +08:00
这里的人一个个逼格真的好高,我自己解决
artlearn
2015-09-03 16:18:26 +08:00
真诚感谢 @aggron
让 BaseMixin 继承 View 类
然后 self.request 就可以
遇到这个问题的新手朋友可以这样做。
artlearn
2015-09-03 16:25:13 +08:00
View 类 原来代码
class View (object ):
"""
Intentionally simple parent class for all views. Only implements
dispatch-by-method and simple sanity checking.
"""

http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']

def __init__(self, **kwargs ):
"""
Constructor. Called in the URLconf; can contain helpful extra
keyword arguments, and other things.
"""
# Go through keyword arguments, and either save their values to our
# instance, or raise an error.
for key, value in six.iteritems (kwargs ):
setattr (self, key, value )

@classonlymethod
def as_view (cls, **initkwargs ):
"""
Main entry point for a request-response process.
"""
# sanitize keyword arguments
for key in initkwargs:
if key in cls.http_method_names:
raise TypeError ("You tried to pass in the %s method name as a "
"keyword argument to %s (). Don't do that."
% (key, cls.__name__))
if not hasattr (cls, key ):
raise TypeError ("%s () received an invalid keyword %r. as_view "
"only accepts arguments that are already "
"attributes of the class." % (cls.__name__, key ))

def view (request, *args, **kwargs ):
self = cls (**initkwargs )
if hasattr (self, 'get') and not hasattr (self, 'head'):
self.head = self.get
self.request = request #就在这里
self.args = args
self.kwargs = kwargs
return self.dispatch (request, *args, **kwargs )
baiyemao
2015-09-03 16:39:50 +08:00
@artlearn 是你提问的方式有问题,请问你和别人也是这样说话的么。
wind3110991
2015-09-04 11:28:36 +08:00
from django.http import HttpResponse
确认导入这个模块后,在类外面单独定义一个方法 getRequest ,用来返回获取 request
然后用一个全局变量 req 调用 getRequest 并保存它
req = getRequest ()
最后实例化 class 时传入 req ,在你的类里用 req

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/218002

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX