Django Rest框架ajax表单提交错误403(禁止)

Moh*_* CH 1 python django ajax python-3.x django-rest-framework

当我尝试提交使用 DRF API 的 ajaxified 表单时,我进入浏览器控制台!

POST http://localhost:8000/api/texts/ 403(禁止)

这是我的 html 文件:

 <form id="text-form" method="POST" action="">
                   

                            <input type="text" name="title" placeholder="Title" class="form-control mb-3 pb-2"
                                maxlength="200" required id="title">
                            <input type="date" name="deadline" placeholder="Deadline" autocomplete="off"
                                class="form-control mb-3" id="myflatpickr">                                         
                      
                            <textarea name="requirements" cols="40" rows="4"
                                placeholder="requirements"
                                class="form-control col mt-3" maxlength="200" required id="requirements"></textarea>

                    <textarea name="document" cols="40" rows="10"
                        placeholder="document"
                        id="editor" class="form-control" required></textarea>

                <button type="submit">Submit</button>
                </form>
Run Code Online (Sandbox Code Playgroud)

这是我的 JavaScript 文件

  $("#text-form").submit(function (event) {
    event.preventDefault();
    $textData = $("#text-form").serialize()
    $.ajax({
      url: "http://localhost:8000/api/texts/",
      method: "POST",
      data: $textData,
      success: function() {
        console.log($textData)
      },
      error: function() {
        console.log("there is an error")

      }
    })

  });
Run Code Online (Sandbox Code Playgroud)

在序列化器.py中:


from django.contrib.auth import get_user_model
from django.contrib.auth.password_validation import validate_password
from rest_framework import serializers
from .models import *



class TextSerializer(serializers.ModelSerializer):
     author = serializers.HiddenField(
         default=serializers.CurrentUserDefault()
     )
     class Meta:
         model = Text
         fields = '__all__'

Run Code Online (Sandbox Code Playgroud)

在我的views.py 文件中:


class ApiTextList(generics.ListCreateAPIView):

    queryset = Text.objects.all()
    serializer_class = TextSerializer
    permission_classes = [
        permissions.AllowAny
    ]


class ApiTextDetail(mixins.RetrieveModelMixin,
                    mixins.UpdateModelMixin,
                    mixins.DestroyModelMixin,
                    generics.GenericAPIView):

    http_method_names = ['get', 'head']
    queryset = Text.objects.all()
    serializer_class = TextSerializer
    permission_classes = [
        permissions.AllowAny
    ]

    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

在 urls.py 中

from django.urls import path
from . import views


urlpatterns = [

    path('api/texts/', views.ApiTextList.as_view()),
    path('api/texts/<int:pk>/', views.ApiTextDetail.as_view()),
    
    
]

Run Code Online (Sandbox Code Playgroud)

注意:当我尝试从 drf 在“localhost:8000/api/texts”中提供的界面添加文本时,我通常添加它

小智 5

现在您已经告诉我们详细信息字段的内容,应该更容易解决您的问题。

Django文档建议您从 cookie 中获取 CSRF 令牌。

它甚至为您提供了以下功能来执行此操作:

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;
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以通过添加这两行来轻松调整自己的代码:

$("#text-form").submit(function (event) {
    event.preventDefault();
    const csrftoken = getCookie('csrftoken'); // HERE: get the token 
    $textData = $("#text-form").serialize()
    $.ajax({
        url: "http://localhost:8000/api/texts/",
        method: "POST",
        data: $textData,
        headers:{"X-CSRFToken": csrftoken }, // HERE: add it to the request header
        success: function() {
            console.log($textData)
        },
        error: function() {
            console.log("there is an error")
        }
    })
});
Run Code Online (Sandbox Code Playgroud)

如果这不起作用,请检查您是否正确使用了会话身份验证

为了回答您的其他询问,您的注册视图在没有 CSRF 令牌的情况下工作是正常的:在 DRF 中,只有您需要进行身份验证的视图才需要它。