我正在使用Vuejs和Django作为我的网络应用程序。 Vuejs负责通过axios发送所有请求(GET,POST,PATCH,DELETE)。
submitContact() {
const {
first_name,
last_name,
email,
hp_no,
twitter,
github,
company
} = this
axios.post(this.apiUrl, {
first_name,
last_name,
email,
hp_no,
twitter,
github,
company,
})
.then()
.catch((err) => {
console.log(err)
});
提交表单时会调用此函数。
用于处理视图中的POST数据:
def contact_data(request):
if request.user.is_authenticated(): # When user is authenticated
if request.method == 'GET': # For viewing records
contacts = Contact.objects.all().filter(user=request.user.id)
contacts_serialized = ContactSerializer(contacts, many=True)
return JsonResponse(contacts_serialized.data, safe=False,)
elif request.method == 'POST': # For creating a record
json_data = json.loads(request.body)
print(json_data)
serializer = ContactSerializer(data=json_data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=status.HTTP_201_CREATED)
return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE': # For deleting a record
pass
else: # When user is not authenticated
return HttpResponse("You are not authorized to access!")
目前,当我提交表单时,视图正在获得这样的JSON POST响应:
{'first_name': 'Jane', 'last_name': 'Doe', 'email': 'jane@gmail.com', 'hp_no': '0111634859', 'twitter': 'jane93', 'github': 'jane23', 'company': 'Jane ltd'}
但序列化程序将其作为无效的序列化数据并返回400响应。我在这里失踪的步骤可能是什么?