I've created a rest-framework view to create an object.

Unfortunately, I get different responses if:

  • I use the browsableAPI interface with raw data : 201 CREATED
  • I use Hurl.it, (see parameters) : 201 CREATED
  • I use curl (curl -d @sample.json -H "Content-Type: application/json" -u admin -i "https://vincentle.pythonanywhere.com/samples/api/create/") : 302 FOUND
  • I use OkHttp/Retrofit in an Android app : 302 FOUND

Can you help me, at least in providing some debug strategies?

views:

class SampleCreateAPIView(ListCreateAPIView):
    queryset = Sample.objects.all()
    serializer_class = SampleSerializer
    permission_classes = (permissions.IsAuthenticated,)

    def perform_create(self, serializer):
        room = serializer.validated_data['room']
        building = room.area.floor.building
        admins = building.customer_account.admin.all()
        if self.request.user in admins:
            super(SampleCreateAPIView, self).perform_create(serializer)
        else:
            raise PermissionDenied(detail=_('You are not in the administrators list for this room'))

serializers:

class SampleSerializer(serializers.ModelSerializer):
    room = serializers.PrimaryKeyRelatedField(many=False, queryset=Room.objects.all())
    wifiaccesspoint_set = WifiAccessPointSerializer(many=True)

    class Meta:
        model = Sample
        fields = ('room', 'wifiaccesspoint_set',)

    def create(self, validated_data):
        wap_data = validated_data.pop('wifiaccesspoint_set')
        sample = Sample(room=validated_data['room'])
        sample.save()
        for wap in wap_data:
            WifiAccessPoint.objects.create(sample=sample, **wap)
        return sample

Edit 1 - Seems a curl problem This command: curl -u admin -i "https://vincentle.pythonanywhere.com/fr/samples/api/create/" -H "Content-Type: application/json" -d @sample.json is working fine and I get a 201 CREATED response.

But this command: curl -d @sample.json -H "Content-Type: application/json" -u admin -i "https://vincentle.pythonanywhere.com/samples/api/create/" is giving me a 302 FOUND response.

What is the difference between those 2 commands?

score:0

302 is a redirection. Since you're using authentication, double check where the redirection goes.

If it's to a login page, my feeling is you're not authenticated because you don't have the right auth scheme configured. curl -u will probably send basic auth which you need to setup on your API (http://www.django-rest-framework.org/api-guide/authentication/#basicauthentication)


Related Query