我对Django REST框架还很陌生,并且尝试为移动应用程序编写API。我面临一个问题,即PUT请求返回响应500(内部服务器错误)的事实之外,它可以正常工作(更新数据)。一些解决此问题的指导将不胜感激。
views.py :
@csrf_exempt
def 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)
models.py:
class Category(models.Model):
name = models.CharField(max_length=25, blank=False)
class Meta:
ordering = ('id',)
serializers.py:
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('id', 'name')
urls.py:
urlpatterns = [
path('category/<int:pk>/', views.category_instance)
]
我试图寻找其他人可能遇到的类似问题,但是我无法为我的问题构建解决方案。
跟踪:
Internal Server Error: /category/1/
Traceback (most recent call last):
File "C:\Users\vaida\Documents\Coding\android-tm-api\venv\lib\site-packages\django\core\handlers\exception.py", line 34,
in inner
response = get_response(request)
File "C:\Users\vaida\Documents\Coding\android-tm-api\venv\lib\site-packages\django\core\handlers\base.py", line 126, in
_get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\vaida\Documents\Coding\android-tm-api\venv\lib\site-packages\django\core\handlers\base.py", line 124, in
_get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\vaida\Documents\Coding\android-tm-api\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, i
n wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\vaida\Documents\Coding\android-tm-api\android_tm_api\api\views.py", line 146, in category_instance
serializer = CategorySerializer(cat, data=request.data)
AttributeError: 'WSGIRequest' object has no attribute 'data'