#django #vue.js #axios
Вопрос:
Мой запрос на получение и удаление работает отлично. Но, получив 400 неверных запросов во время вызова метода POST или PUT. И для вашего сведения, мой фреймворк Django rest отлично работает в POST-MAN и в моем местном http://127.0.0.1:8000/doctor. И я тоже включаю изображение своей локальной машины.
Это работает нормально. В моем коде Axios:
data(){ return{ doctors:[], modalTitle:"", DoctorName:"", DoctorId:0, DoctorNameFilter:"", DoctorIdFilter:"", doctorsWithoutFilter:[] } }, methods:{ refreshData(){ axios.get(variables.API_URL "doctor/") .then((response)=gt;{ this.doctors=response.data; this.doctorsWithoutFilter=response.data; }); }, addClick(){ this.modalTitle="Add Doctor"; this.DoctorId=0; this.DoctorName=""; }, editClick(doc){ this.modalTitle="Edit Doctor"; this.DoctorId=doc.id; this.DoctorName=doc.name; }, createClick(){ axios.post(variables.API_URL "doctor/",Qs.stringify({ data:this.DoctorName })) .then((response)=gt;{ this.refreshData(); alert(response.data); }); }, updateClick(){ axios.put(variables.API_URL "doctor/" this.DoctorId, Qs.stringify({ data:this.DoctorName })) .then((response)=gt;{ this.refreshData(); alert(response.data); }); }, deleteClick(id){ if(!confirm("Are you sure?")){ return; } axios.delete(variables.API_URL "doctor/" id) .then((response)=gt;{ this.refreshData(); alert(response.data); }); }, FilterFn(){ var DoctorIdFilter=this.DoctorIdFilter; var DoctorNameFilter=this.DoctorNameFilter; this.doctors=this.doctorsWithoutFilter.filter( function(el){ return el.DoctorId.toString().toLowerCase().includes( DoctorIdFilter.toString().trim().toLowerCase() )amp;amp; el.DoctorName.toString().toLowerCase().includes( DoctorNameFilter.toString().trim().toLowerCase() ) }); }, sortResult(prop,asc){ this.doctors=this.doctorsWithoutFilter.sort(function(a,b){ if(asc){ return (a[prop]gt;b[prop])?1:((a[prop]lt;b[prop])?-1:0); } else{ return (b[prop]gt;a[prop])?1:((b[prop]lt;a[prop])?-1:0); } }) } }, mounted:function(){ this.refreshData(); } }
My Django settings.py:
""" Django settings for DrAppointment project. Generated by 'django-admin startproject' using Django 3.2.8. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-s6!#d2y#rlptramp;#e) 0e^=m=n(amp;!zrqa$byd#pwbgzpogvo8qe' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'appointment', 'rest_framework', 'corsheaders', ] CORS_ORIGIN_ALLOW_ALL = True MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.common.CommonMiddleware', ] ROOT_URLCONF = 'DrAppointment.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'DrAppointment.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Europe/Berlin' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # REST_FRAMEWORK Settings REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) }
В моем view.py :
from django.shortcuts import render, HttpResponse from .models import Doctors, Appointment from .serializers import DoctorsSerializer, AppointmentSerializer from django.http import JsonResponse from rest_framework.parsers import JSONParser from rest_framework.decorators import api_view, permission_classes from rest_framework.response import Response from rest_framework import status, generics from rest_framework import permissions from rest_framework.decorators import APIView # from django.views.decorators.csrf import csrf_exempt @permission_classes((permissions.AllowAny,)) class DoctorList(generics.ListCreateAPIView): queryset = Doctors.objects.all() serializer_class = DoctorsSerializer @permission_classes((permissions.AllowAny,)) class DoctorDetails(generics.RetrieveUpdateDestroyAPIView): queryset = Doctors.objects.all() serializer_class = DoctorsSerializer
В Моем urls.py:
from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from appointment import views # from .views import DoctorList, DoctorDetails # from .views import doctor_list, doctor_details, appointment_list, appointment_details urlpatterns = [ path('doctor/', views.DoctorList.as_view()), path('doctor/lt;int:pkgt;', views.DoctorDetails.as_view()), # path('appointment/', AppointmentList.as_view()), # path('appointment/lt;int:pkgt;', AppointmentDetails.as_view()), ]
Комментарии:
1. Вам нужно отладить сетевой запрос в devtools. Там вы можете четко видеть, что отправляется на сервер и чем это отличается от успешной публикации. То, что вы показываете в консоли, — это всего лишь симптом.
2. Хорошо, сэр, я проверю это и дам вам знать.