Django rest框架 AJAX 表单提交错误403(禁止)

ddhy6vgd  于 2022-11-19  发布在  Go
关注(0)|答案(3)|浏览(136)

当我试图提交我的ajaxified形式,与DRF API的工作,我在浏览器控制台!
发布(禁止)
下面是我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>

这是我的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")

      }
    })

  });

中serializers.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__'

在我的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)

中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()),
    
    
]

注意:当我试图从接口添加一个文本时,drf在“localhost:8000/api/texts”中提供,我通常会添加它

pgky5nke

pgky5nke1#

既然您已将详细信息字段的内容告诉我们,解决问题应该会更容易。
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;
}

然后,您可以通过添加以下两行代码轻松地修改自己的代码:

$("#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")
        }
    })
});

如果不起作用,请检查是否正确使用了会话身份验证。
为了回答您的其他问题,您的注册视图在没有CSRF令牌的情况下正常工作:在DRF中,只有需要进行身份验证的视图才需要它。

rqcrx0a6

rqcrx0a62#

您将收到错误403,这意味着服务器理解请求但拒绝授权它。您需要在发送 AJAX 请求时添加一个授权令牌。
您可以使用这个来授权页面上的令牌。

<script type="text/javascript"> window.CSRF_TOKEN = "{{ csrf_token }}"; </script>

然后,您必须将令牌添加到 AJAX 请求中。

$.ajax({
  url: "http://localhost:8000/api/texts/",
  method: "POST",
  data: $textData,

  csrfmiddlewaretoken: window.CSRF_TOKEN,

  success: function() {
    console.log($textData)
  },
  error: function() {
    console.log("there is an error")

  }
})
nbysray5

nbysray53#

试试这个,对于禁止403

$.ajax({
  url: "http://localhost:8000/api/texts/",
  method: "POST",
  data: $textData,
  contentType: "application/json;charset=utf-8",
  dataType: "json",
  headers: {"X-CSRFToken": "{{ csrf_token }}"},

  success: function() {
    console.log($textData)
  },
  error: function() {
    console.log("there is an error")
  }
})

相关问题