简体   繁体   English

Django API测试:CSRF异常

[英]Django API testing: CSRF exception

I'm trying to test updating a value, in this example a location's timeslot (each location can have many timeslots, a timeslot has 1 location), with a PUT request. 我正在尝试测试更新值,在此示例中,是一个位置的时隙(每个位置可以有多个时隙,一个时隙有1个位置),并带有PUT请求。 I'd like to update location_id 1 , timeslot 1 's filled attribute to true . 我想将location_id 1 (时隙1的filled属性)更新为true

I'm getting a "CSRF Failed: CSRF token missing or incorrect." 我收到"CSRF Failed: CSRF token missing or incorrect." error even though I've added @csrf_exempt above the function definition in views. 错误,即使我在视图中的函数定义上方添加了@csrf_exempt

DHC PUT Request: DHC PUT请求:

  • localhost:1234/v1.0/location/1/timeslots/1 本地主机:1234 / v1.0 / location / 1 / timeslots / 1
  • body: {"filled" : "true"} 正文:{“ filled”:“ true”}

URL Patterns: 网址格式:

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

Views.py: 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: 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)

I'm not sure why I am getting the csrf issue despite the exemption. 尽管有豁免,我不确定为什么会收到csrf问题。

try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM