Django:禁止(未设置 CSRF cookie。):用于 DELETE 请求
Django: Forbidden (CSRF cookie not set.): for DELETE request
在高层次上,我的 GET、POST 和 PUT 请求都在工作。当我尝试 DELETE 请求时,出现以下错误:"Forbidden (CSRF cookie not set.): /department/1
[07/Dec/2021 12:28:24] "删除 /department/1 HTTP/1.1" 403 2870
我正在按照以下教程构建我的第一个 Angular/Python Django/SQLite 应用程序。到目前为止,我正在使用 Postman 处理所有请求。尚未构建 angular 部分。
由于我使用的是较新版本的 Django,因此出现了一些差异。
https://www.youtube.com/watch?v=1Hc7KlLiU9w
https://github.com/ArtOfEngineer/PythonDjangoAngular10/tree/master/DjangoAPI
我还有大约 31 分钟
这是我在 virtualEnv 中的安装
- asgiref==3.4.1
- Django==4.0
- django-cors-headers==3.10.1
- djangorestframework==3.12.4
- pytz==2021.3 - 我下面的示例没有安装它。我需要把它拿到 运行
- sqlparse==0.4.2
- tzdata==2021.5
PracticeApp/views.py
#PracticeApp/views.py
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from django.http.response import JsonResponse
from PracticeApp.models import Departments,
from PracticeApp.serializers import DepartmentSerializer
@csrf_exempt
def departmentApi(request, id=0):
if request.method=='GET':
departments = Departments.objects.all()
departments_serializer = DepartmentSerializer(departments, many=True)
return JsonResponse(departments_serializer.data, safe=False)
elif request.method=='POST':
department_data=JSONParser().parse(request)
department_serializer = DepartmentSerializer(data=department_data)
if department_serializer.is_valid():
department_serializer.save()
return JsonResponse("Added Successfully!!" , safe=False)
return JsonResponse("Failed to Add.",safe=False)
elif request.method=='PUT':
department_data = JSONParser().parse(request)
department=Departments.objects.get(DepartmentId=department_data['DepartmentId'])
department_serializer=DepartmentSerializer(department,data=department_data)
if department_serializer.is_valid():
department_serializer.save()
return JsonResponse("Updated Successfully!!", safe=False)
return JsonResponse("Failed to Update.", safe=False)
elif request.method=='DELETE':
department=Departments.objects.get(DepartmentId=id)
department.delete()
return JsonResponse("Deleted Successfully!!", safe=False)
在 urls.py 你会看到我正在使用
- 从django.urls导入路径而不是
- 从 django.conf.urls 导入 url.
因此我使用 urlpatterns=[path()] 而不是 urlpatterns=[url()] 就像示例中使用的
PracticeApp/urls.py
#PracticeApp/urls.py
from django.urls import path
from PracticeApp import views
urlpatterns=[
path(r'department/',views.departmentApi),
path(r'department/([0-9]+)',views.departmentApi), #delete method
]
DjangoAPI/urls.py
#DjangoAPI/urls.py
from django.urls import include, path
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
path(r'', include('PracticeApp.urls'))
]
以下是来自 settings.py 的相关片段。
DjangoAPI/settings.py
#DjangoAPI/settings.py
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'PracticeApp.apps.PracticeappConfig',
'rest_framework',
]
CORS_ORIGIN_ALLOW_ALL = True
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'DjangoAPI.urls'
PracticeApp/serializers.py
#PracticeApp/serializers.py
from rest_framework import serializers
from PracticeApp.models import Departments, Employees
class DepartmentSerializer(serializers.ModelSerializer):
class Meta:
model = Departments
fields = ('DepartmentId',
'DepartmentName')
您无法在您的视图中获取要删除的对象的 ID,并且您使用的是视图中指定的默认值,即零。所以它找不到对象。更改您的删除 url 如下:
path(r'department/<int:department_id>',views.departmentApi)
在您看来:
department=Departments.objects.get(DepartmentId=department_id)
在高层次上,我的 GET、POST 和 PUT 请求都在工作。当我尝试 DELETE 请求时,出现以下错误:"Forbidden (CSRF cookie not set.): /department/1 [07/Dec/2021 12:28:24] "删除 /department/1 HTTP/1.1" 403 2870
我正在按照以下教程构建我的第一个 Angular/Python Django/SQLite 应用程序。到目前为止,我正在使用 Postman 处理所有请求。尚未构建 angular 部分。
由于我使用的是较新版本的 Django,因此出现了一些差异。
https://www.youtube.com/watch?v=1Hc7KlLiU9w https://github.com/ArtOfEngineer/PythonDjangoAngular10/tree/master/DjangoAPI
我还有大约 31 分钟
这是我在 virtualEnv 中的安装
- asgiref==3.4.1
- Django==4.0
- django-cors-headers==3.10.1
- djangorestframework==3.12.4
- pytz==2021.3 - 我下面的示例没有安装它。我需要把它拿到 运行
- sqlparse==0.4.2
- tzdata==2021.5
PracticeApp/views.py
#PracticeApp/views.py
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from django.http.response import JsonResponse
from PracticeApp.models import Departments,
from PracticeApp.serializers import DepartmentSerializer
@csrf_exempt
def departmentApi(request, id=0):
if request.method=='GET':
departments = Departments.objects.all()
departments_serializer = DepartmentSerializer(departments, many=True)
return JsonResponse(departments_serializer.data, safe=False)
elif request.method=='POST':
department_data=JSONParser().parse(request)
department_serializer = DepartmentSerializer(data=department_data)
if department_serializer.is_valid():
department_serializer.save()
return JsonResponse("Added Successfully!!" , safe=False)
return JsonResponse("Failed to Add.",safe=False)
elif request.method=='PUT':
department_data = JSONParser().parse(request)
department=Departments.objects.get(DepartmentId=department_data['DepartmentId'])
department_serializer=DepartmentSerializer(department,data=department_data)
if department_serializer.is_valid():
department_serializer.save()
return JsonResponse("Updated Successfully!!", safe=False)
return JsonResponse("Failed to Update.", safe=False)
elif request.method=='DELETE':
department=Departments.objects.get(DepartmentId=id)
department.delete()
return JsonResponse("Deleted Successfully!!", safe=False)
在 urls.py 你会看到我正在使用
- 从django.urls导入路径而不是
- 从 django.conf.urls 导入 url.
因此我使用 urlpatterns=[path()] 而不是 urlpatterns=[url()] 就像示例中使用的
PracticeApp/urls.py
#PracticeApp/urls.py
from django.urls import path
from PracticeApp import views
urlpatterns=[
path(r'department/',views.departmentApi),
path(r'department/([0-9]+)',views.departmentApi), #delete method
]
DjangoAPI/urls.py
#DjangoAPI/urls.py
from django.urls import include, path
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
path(r'', include('PracticeApp.urls'))
]
以下是来自 settings.py 的相关片段。
DjangoAPI/settings.py
#DjangoAPI/settings.py
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'PracticeApp.apps.PracticeappConfig',
'rest_framework',
]
CORS_ORIGIN_ALLOW_ALL = True
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'DjangoAPI.urls'
PracticeApp/serializers.py
#PracticeApp/serializers.py
from rest_framework import serializers
from PracticeApp.models import Departments, Employees
class DepartmentSerializer(serializers.ModelSerializer):
class Meta:
model = Departments
fields = ('DepartmentId',
'DepartmentName')
您无法在您的视图中获取要删除的对象的 ID,并且您使用的是视图中指定的默认值,即零。所以它找不到对象。更改您的删除 url 如下:
path(r'department/<int:department_id>',views.departmentApi)
在您看来:
department=Departments.objects.get(DepartmentId=department_id)