Django REST框架:' WSGIRequest'对象没有属性' query_params'

时间:2017-03-19 21:37:18

标签: python django django-rest-framework

我正在学习DRF,并尝试打印print request.query_params。但得到了错误:

    print request.query_params
AttributeError: 'WSGIRequest' object has no attribute 'query_params'

代码:

class CourseDetailView(generics.RetrieveAPIView):
    queryset = Course.objects.all()
    serializer_class = CourseSerializer

    def dispatch(self, request, *args, **kwargs):
        print request.user
        print 'CourseDetailView dispatch:', request.META
        #print request.data
        """
        print 'parsers', request.parsers
        print request.accepted_renderer
        print 'authenticators', request.authenticators
        """
        #print 'accepted_media_type', request.accepted_media_type
        print request.META['HTTP_ACCEPT']
        print 'method', request.method
        print 'content_type', request.content_type
        print 'query_params'
        print request.query_params # Here

        return super(CourseDetailView, self).dispatch(request, *args, **kwargs)

我的部分设置:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'api',
]

# DJANGO REST FRAMEWORK
REST_FRAMEWORK = {
}

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

1 个答案:

答案 0 :(得分:3)

dispatch是在基于类的视图中调用的第一个方法,它是所有设置发生的地方 - 包括,在API视图的情况下,Django请求对象的包装DRF扩展。通过覆盖它,您已经阻止了任何代码的运行,因此您只需要基本的Django请求。

通常,您应该避免覆盖dispatch。使用更合适的方法,例如get