当我尝试通过下面显示的视图文件在远程计算机中进行发布请求时,收到HTTP 400错误请求,但是,当我在本地计算机中执行相同的请求时,它会很好地工作。
远程计算机(在EC2计算机上使用docker)
serializers.py
from rest_framework import serializers
from .models import irrigation, moisture
class IrrigationSerializer(serializers.ModelSerializer):
class Meta:
model = irrigation
fields = '__all__'
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.urls import reverse
from .models import irrigation, moisture
from .serializers import IrrigationSerializer
from rest_framework import viewsets
from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view, action
class irrigationValues(viewsets.ModelViewSet):
queryset = irrigation.objects.all()
serializer_class = IrrigationSerializer
def list(self, request):
serializer = self.serializer_class(self.queryset, many = True)
return Response(serializer.data)
def dashboard(request):
irrigations = irrigation.objects.all()
return render(request, 'dashboard.html',{'irrigations':irrigations})
@api_view(['POST'])
def addIrrigation(request):
addIrrigation = IrrigationSerializer(data=request.data)
print(request.data)
if addIrrigation.is_valid():
addIrrigation.save()
return Response({"data":"Value added"},status = status.HTTP_201_CREATED)
else:
error_details = []
for key in addIrrigation.errors.keys():
error_details.append({"field": key, "message": addIrrigation.errors[key][0]})
data = {
"Error": {
"status": 400,
"message": "Your submitted data was not valid - please correct the below errors",
"error_details": error_details
}
}
return Response(data, status=status.HTTP_400_BAD_REQUEST)
我从本地计算机上获得的结果是:
{
"data":"Value added"
}
“ print(request.data)”的输出为:
{'hardware_id': '001', 'temperature': 23, 'valve_status': 'Close'}
[02/Jul/2019 11:38:35] "POST /dashboard/addirrigation/ HTTP/1.1" 201 5680
我从远程计算机上得到的结果是:
{
"Error": {
"status": 400,
"message": "Your submitted data was not valid - please correct the below errors",
"error_details": [
{
"field": "hardware_id",
"message": "This field is required."
},
{
"field": "temperature",
"message": "This field is required."
},
{
"field": "valve_status",
"message": "This field is required."
}
]
}
}
“ print(request.data)”的输出为:
<QueryDict: {'_content_type': ['application/json'], '_content': ['{\r\n "hardware_id": "001",\r\n "temperature": 23,\r\n "valve_status": "Close"\r\n}']}>Bad Request: /dashboard/addirrigation/
注意:也许这对您来说很明显,但是我需要提及的是,当我使用“ HTML表单”通过drf进行发布请求时,该发布已成功提交,但是当我使用“原始数据”选项将其发布。
答案 0 :(得分:0)
如问题所附图片所示,当我尝试通过API门户添加数据时,收到HTTP 400响应,但是当我使用邮递员并将查询的内容类型选择为“ application / json”时数据已成功发布(HTTP 201响应)。