Django API测试:CSRF异常

时间:2015-10-05 21:54:42

标签: python django django-views django-rest-framework

我正在尝试测试更新值,在此示例中是位置的时间段(每个位置可以有多个时隙,时隙有1个位置),带有PUT请求。我想将location_id 1,时间段1的填充属性更新为true

即使我在视图中的函数定义上方添加了"CSRF Failed: CSRF token missing or incorrect.",我也收到@csrf_exempt错误。

DHC PUT请求:

  • 本地主机:1234 / 1.0 /位置/ 1 /时隙/ 1
  • body:{“filled”:“true”}

网址格式:

...
url(r'^v1.0/location/?/timeslots/?', content_views.location_detail),
...

Views.py:

class LocationViewSet(viewsets.ModelViewSet):
    queryset = Location.objects.all()
    serializer_class = LocationSerializer
    http_method_names = ['get', 'post', 'put']

@api_view(['GET', 'POST', 'PUT',])
@csrf_exempt
def location_detail(request, pk):

    try:
        location = Location.objects.get(pk=pk)
    except Location.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = LocationSerializer(location)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = LocationSerializer(location, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Models.py:

class Location(models.Model):
    ...

class Timeslot(models.Model):
    name = models.CharField(max_length=200)
    time = models.DateTimeField(auto_now_add=True, null=True)
    location_id = models.ForeignKey(Location, related_name='timeslots')
    filled = models.BooleanField(default=False)

我不确定为什么即使获得豁免,我也会收到csrf问题。

1 个答案:

答案 0 :(得分:0)

试试这个:

@csrf_exempt
@api_view(['GET', 'POST', 'PUT',])
def location_detail(request, pk):
    ...