因此,我遵循这个教程https://youtu.be/hISSGMafzvU,与我不同的方法(而不是作为一个做应用程序,我试图使它成为一个诊所管理系统)。
因此,我面临的问题是,我的api正在接收数据,没有错误,加上我从本地服务器获得200状态代码,这意味着一切正常,但它不是因此数据没有被存储在数据库中的某种原因。
下面是代码:
models.py
class Employee(models.Model):
fullname = models.CharField(max_length = 250)
age = models.DateField(null=True, blank=True)
gender = models.CharField(max_length=10,
choices=(('Male', 'Male'), ('Female', 'Female')), default='Male')
usertype = models.CharField(max_length = 50, choices=
(('Admin','Admin'),('Doctor','Doctor'),('Receptionist','Receptionist')),
default='Receptionist')
def __str__(self):
return self.fullname
class Patient(models.Model):
fullname = models.CharField(max_length = 250)
def __str__(self):
return self.fullname
class Appointments(models.Model):
Paitent_Attending = models.ForeignKey(Patient, on_delete= models.CASCADE)
Doctor_Attending = models.ForeignKey(Employee, on_delete= models.CASCADE)
appointment_date = models.DateField()
def __str__(self):
return self.Paitent_Attending.fullname
serializers.py
from rest_framework import serializers
from .models import Employee,Patient,Appointments
class PatientSerializers(serializers.ModelSerializer):
class Meta:
model = Patient
fields = '__all__'
class EmployeeSerializers(serializers.ModelSerializer):
class Meta:
model = Employee
fields = '__all__'
class AppointmentsSerializers(serializers.ModelSerializer):
class Meta:
model = Appointments
fields = '__all__'
views.py
from django.shortcuts import render
from rest_framework import generics
from .models import *
from .serializers import *
from django.http import JsonResponse
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET'])
def apiView(request):
api_urls = {
'Patient List':'/patient-list/',
'Employee List':'/employee-list/',
'Appointments List':'/appointments-list/',
'Patient View':'/patient-detail/<str:pk>/',
'Employee View':'/employee-detail/<str:pk>/',
'Appointments View':'/appointments-detail/<str:pk>/',
'Add Patient':'/add-patient/',
'Edit Patient':'/patient-edit/<str:pk>/',
'Delete Patient':'/patient-delete/<str:pk>/',
'Add Employee':'/add-employee/',
'Edit Employee':'/employee-edit/<str:pk>/',
'Delete Employee':'/employee-delete/<str:pk>/',
'Add Appointments':'/add-appointments/',
'Edit Appointments':'/appointments-edit/<str:pk>/',
'Delete Appointments':'/appointments-delete/<str:pk>/',
}
return Response(api_urls)
#views for listing All
@api_view(['GET'])
def patientList(request):
patient = Patient.objects.all()
serializer = PatientSerializers(patient, many=True)
return Response(serializer.data)
@api_view(['GET'])
def employeesList(request):
employee = Employee.objects.all()
serializer = EmployeeSerializers(employee, many=True)
return Response(serializer.data)
@api_view(['GET'])
def appointmentsList(request):
appointments = Appointments.objects.all()
serializer = AppointmentsSerializers(appointments, many=True)
return Response(serializer.data)
#Views for Details
@api_view(['GET'])
def patientDetails(request,pk):
patient = Patient.objects.get(id=pk)
serializer = PatientSerializers(patient, many=False)
return Response(serializer.data)
@api_view(['GET'])
def employeeDetails(request,pk):
employee = Employee.objects.get(id=pk)
serializer = EmployeeSerializers(employee, many=False)
return Response(serializer.data)
@api_view(['GET'])
def appointmentsDetails(request,pk):
appointments = Appointments.objects.get(id=pk)
serializer = AppointmentsSerializers(appointments, many=False)
return Response(serializer.data)
#Views for Create New
@api_view(['POST'])
def addPatient(request):
serializer = PatientSerializers(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
@api_view(['POST'])
def addEmployee(request):
serializer = EmployeeSerializers(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
@api_view(['POST'])
def addAppointment(request):
serializer = AppointmentsSerializers(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
#Views for updating & editing
@api_view(['POST'])
def editPatient(request,pk):
patient = Patient.objects.get(id=pk)
serializer = PatientSerializers(instance=patient, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
@api_view(['POST'])
def editEmployee(request,pk):
employee = Employee.objects.get(id=pk)
serializer = EmployeeSerializers(instance=employee, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
@api_view(['POST'])
def editAppointment(request,pk):
appointment = Appointments.objects.get(id=pk)
serializer = AppointmentsSerializers(instance=appointment, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
#Views for updating & editing
@api_view(['DELETE'])
def deletePatient(request,pk):
patient = Patient.objects.get(id=pk)
patient.delete()
return Response("Patient was successfully deleted")
@api_view(['DELETE'])
def deleteEmployee(request,pk):
employee = Employee.objects.get(id=pk)
employee.delete()
return Response("Employee was successfully deleted")
@api_view(['DELETE'])
def deleteAppointment(request,pk):
appointment = Appointments.objects.get(id=pk)
appointment.delete()
return Response("Appointment was successfully deleted")
通过fetch api发送数据的JS。
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
const csrftoken = getCookie('csrftoken');
var form = document.getElementById('newPatient');
form.addEventListener('submit', function(e) {
e.preventDefault()
console.log('form submited');
var url = 'http://127.0.0.1:8000/api/add-patient/'
var Fullname = document.getElementById('Fullname').value
fetch(url, {
method: 'POST',
headers:{
'Content-Type': 'application/json',
'X-CSRFToken' : csrftoken,
},
body: JSON.stringify({'Fullname':Fullname})
}
)
})
我对api世界还是个新手,我在这里很困惑,救命啊!
1条答案
按热度按时间wwtsj6pe1#
这是一个愚蠢的错误,当你不把重点放在名字哈哈。
addPatient属性
fullname
的名称,获取API尝试将数据发送到不存在的Fullname
大写F,由于www.example.com中的此代码,导致数据未保存views.py序列化程序正在接收数据,但由于大写字母F,它与addPatient属性(fullname而非Fullname)不匹配,这导致序列化程序无效,因此无法满足if语句条件,因此无法保存数据xD,叹息