Python Django API测试:CSRF异常
我试图用PUT请求更新一个值,在本例中是一个位置的时隙(每个位置可以有许多时隙,一个时隙有一个位置)。我想将location\u idPython Django API测试:CSRF异常,python,django,django-views,django-rest-framework,Python,Django,Django Views,Django Rest Framework,我试图用PUT请求更新一个值,在本例中是一个位置的时隙(每个位置可以有许多时隙,一个时隙有一个位置)。我想将location\u id1,timeslot1的filled属性更新为true 我收到一个“CSRF失败:CSRF令牌丢失或不正确。”错误,尽管我在视图中的函数定义上方添加了@CSRF\u emption DHCPUT请求: localhost:1234/v1.0/location/1/timeslots/1 正文:{“已填充”:“真”} URL模式: ... url(r'^v1.0
1
,timeslot1
的filled属性更新为true
我收到一个“CSRF失败:CSRF令牌丢失或不正确。”
错误,尽管我在视图中的函数定义上方添加了@CSRF\u emption
DHCPUT
请求:
- localhost:1234/v1.0/location/1/timeslots/1
- 正文:{“已填充”:“真”}
...
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
问题。试试这个:
@csrf_exempt
@api_view(['GET', 'POST', 'PUT',])
def location_detail(request, pk):
...
当您使用
会话身份验证时,DRF公然忽略@csrf\u emption
。