我正在尝试测试更新值,在此示例中是位置的时间段(每个位置可以有多个时隙,时隙有1个位置),带有PUT请求。我想将location_id 1
,时间段1
的填充属性更新为true
。
即使我在视图中的函数定义上方添加了"CSRF Failed: CSRF token missing or incorrect."
,我也收到@csrf_exempt
错误。
DHC PUT
请求:
网址格式:
...
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
问题。
答案 0 :(得分:0)
试试这个:
@csrf_exempt
@api_view(['GET', 'POST', 'PUT',])
def location_detail(request, pk):
...