我是 Django REST 框架的新手,我尝试为我的移动应用程序编写 API。我面临一个问题,除了它返回响应 500(内部服务器错误)之外,PUT 请求工作正常(更新数据)。对解决此问题的一些指导将不胜感激。视图.py:@csrf_exemptdef category_instance(request, pk): """ Returns Category instance """ try: cat = Category.objects.get(pk=pk) except Category.DoesNotExist: return HttpResponse("Error: category does not exist", status=404) if request.method == 'GET': serializer = CategorySerializer(cat, many=False) return JsonResponse(serializer.data, safe=False) elif request.method == 'PUT': serializer = CategorySerializer(cat, data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, 200) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': cat.delete() return HttpResponse(status=204) else: return HttpResponse(status=400)模型.py:class Category(models.Model): name = models.CharField(max_length=25, blank=False) class Meta: ordering = ('id',)序列化程序.py:class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'name')网址.py:urlpatterns = [ path('category/<int:pk>/', views.category_instance)]我试图寻找其他人可能遇到的类似问题,但我无法为我的问题构建解决方案。
添加回答
举报
0/150
提交
取消