我创建了一个休息框架视图来创建一个对象。
不幸的是,如果出现以下情况我会得到不同的答案:
curl -d @sample.json -H "Content-Type: application/json" -u admin -i "https://vincentle.pythonanywhere.com/samples/api/create/"
):302 FOUND 你能帮助我,至少在提供一些调试策略方面吗?
的观点:
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'))
串行器:
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
编辑1 - 似乎卷曲问题
这个命令:curl -u admin -i "https://vincentle.pythonanywhere.com/fr/samples/api/create/" -H "Content-Type: application/json" -d @sample.json
工作正常,我收到201 CREATED响应。
但是这个命令:curl -d @sample.json -H "Content-Type: application/json" -u admin -i "https://vincentle.pythonanywhere.com/samples/api/create/"
给了我一个302 FOUND响应。
这两个命令有什么区别?
答案 0 :(得分:0)
302是重定向。由于您正在使用身份验证,请仔细检查重定向的位置。
如果是登录页面,我的感觉是您未经过身份验证,因为您没有配置正确的身份验证方案。 curl -u
可能会发送您需要在API上设置的基本身份验证(http://www.django-rest-framework.org/api-guide/authentication/#basicauthentication)