2015-10-05 68 views
0

我試圖測試更新值,在這個例子中,一個位置的時隙(每個位置可以有多個時隙,一個時隙有1個位置),帶有一個PUT請求。我想更新location_id 1,時隙1的填充屬性爲trueDjango API測試:CSRF異常

即使我在視圖中的函數定義之上添加了@csrf_exempt,我仍然收到"CSRF Failed: CSRF token missing or incorrect."錯誤。

DHC PUT請求:

  • 本地主機:1234/1.0 /位置/ 1 /時隙/ 1
  • 體:{ 「填充」: 「真」}

URL模式:

... 
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

DRF當你使用'SessionAuthentication'公然無視'@ csrf_exempt'。 – knbk

回答

0

試試這個:

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