Django请求未定义

时间:2017-03-20 04:42:16

标签: django http

我正在尝试实现一个Http服务器,并在我的程序中有以下代码行

if request.method == 'GET'

我一直收到一个没有定义请求的NameError。

这是我的导入

from django.shortcuts import render

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from rest_framework import status
from people.models import People
from people.serializers import PeopleSerializer

我无法弄清楚为什么在我导入的Http中它是一个有效对象时,没有定义请求。

完整代码段

@csrf_exempt
def people_detail(people, pk):
    try:
        people = People.objects.get(pk=pk)
    except People.DoesNotExist:
        return HttpResponse(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        people_serializer = PeopleSerializer(people)
        return JSONResponse(people_serializer.data)

    elif request.method == 'PUT':
        people_data = JSONParser().parse(request)
        people_serializer = PeopleSerializer(people, data = people_data)
        if people_serializer.is_valid():
            people_serializer.save()
            return JSONResponse(people_serializer.data)
        return JSONResponse(people_serializer.errors,
        status = status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        people.delete()
        return HttpResponse(status=status.HTTP_204_NO_CONTENT)

人/ views.py

from django.conf.urls import url
from people import views

urlpatterns = [
    url(r'^people/$', views.people_list),
    url(r'people/(?P<pk>[0-9]+)/$', views.people_detail),
]

人/ peopleapi / urls.py

from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('people.urls')),
]

1 个答案:

答案 0 :(得分:0)

request应该是视图的第一个参数。

@csrf_exempt
def people_detail(request, pk):
...