首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我的API正在发送数据,但它不会存储在后端。

我的API正在发送数据,但它不会存储在后端。
EN

Stack Overflow用户
提问于 2022-11-24 14:19:20
回答 1查看 42关注 0票数 0

因此,我遵循这个教程https://youtu.be/hISSGMafzvU,用我的不同方法(而不是一个要做的应用程序,我试图使它成为一个诊所管理系统)。

所以我面临的问题是我的api正在接收数据,而且没有错误,而且我从本地服务器获得了200个状态代码,这意味着一切正常,但是由于某种原因,数据没有被存储在DB中。

这是代码:

models.py

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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。

代码语言:javascript
运行
复制
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世界的新手,我在这里很困惑,救命!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-11-26 13:17:59

这是那些愚蠢的错误之一,当你不把注意力放在名字上的时候。

addPatient属性fullname的名称,fetch api试图将数据发送到不存在的Fullname大写字母F,这导致数据由于在views.py中的代码而不被保存。

代码语言:javascript
运行
复制
def addPatient(request):
   serializer = PatientSerializers(data=request.data)

   if serializer.is_valid():
       serializer.save()

   return Response(serializer.data)

序列化程序正在接收数据,但由于大写F不匹配addPatient属性,即全名而不是全名,这导致序列化程序无效,从而不满足if语句条件,从而无法保存数据xD,请叹

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74562189

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档