gpt4 book ai didi

django - { "detail": "CSRF Failed: CSRF token missing or incorrect." }

转载 作者:行者123 更新时间:2023-12-03 08:18:48 32 4
gpt4 key购买 nike

enter image description here

大家好。我尝试使用 DRF 和 Postman 在我的应用程序中注册新产品。当我发送请求时,我收到此错误。问题出在我的 csrf_token 上。如果您能帮助我,我将不胜感激......

这是我的观点

class ProductViewSet(viewsets.ModelViewSet):
authentication_classes = (SessionAuthentication,TokenAuthentication)
permission_classes = [IsAdminUser]
queryset = ProductInfo.objects.all().order_by('-id')
serializer_class = ProductSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ['title','code','owner__username']

我的 GET 请求没有任何问题。

最佳答案

Django 默认在 POST 请求中需要 CSRF token 。以避免 CSRF token 。

不要使用SessionAuthentication作为身份验证类,因为它会强制您添加CSRF token 。

如果您仍然想使用SessionAuthentication,那么您可以使用它覆盖

defforce_csrf(self, request): 方法

尝试下面这个:

from rest_framework.authentication import SessionAuthentication

class CsrfExemptSessionAuthentication(SessionAuthentication):
def enforce_csrf(self, request):
pass

并在您的 View 中使用它:

authentication_classes = (CsrfExemptSessionAuthentication ,TokenAuthentication) 

如果您想在全局范围内使用它,可以将其放置在 REST_FRAMEWORK settings.py 文件中,如下所示:

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
'myapp.path-to-file.CsrfExemptSessionAuthentication'
],
}

请确保在 REST_FRAMEWORK 设置中添加正确的文件路径

使用 token 进行身份验证。

您必须这样请求:

curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'

另请确保您已将其添加到 INSTALLED_APP 中:

INSTALLED_APPS = [
''''
'rest_framework',
'rest_framework.authtoken',
]

更多详细信息可以在这里找到:https://www.django-rest-framework.org/api-guide/authentication/

关于django - { "detail": "CSRF Failed: CSRF token missing or incorrect." },我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68507396/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com