简体   繁体   English

错误:使用 django rest 框架时禁止(CSRF 令牌丢失或不正确。)

[英]Error :Forbidden (CSRF token missing or incorrect.) while using django rest framework

I use in my study project django rest framework.I get an error 403 Forbidden (CSRF token missing or incorrect, when I try to save using the POST method. Here is my code html我在我的学习项目中使用 django rest 框架。当我尝试使用 POST 方法保存时,出现错误 403 Forbidden (CSRF token missing or incorrect, Here is my code html

<form id = "product_form" method = "post">
    {% csrf_token %}
    <input type = "hidden" name = "id" id = "id">
    <p>Назвние:<input name = "name" id = "name"></p>
    <p><input type = "reset" value = "Oчистить"></p>
    <input type = "submit" value = "Сохранить">
</form>

Here is my code js:这是我的代码js:

let productUpdater = new XMLHttpRequest();
productUpdater.addEventListener('readystatechange', () => {

        if (productUpdater.readyState == 4) {
            if ((productUpdater.status == 200) || (productUpdater.status == 201)) {
                listLoad();
                name.form.reset();
                id.value = '';
            } else {
                window.alert(productUpdater.statusText)
            }
        }
    }
);


name.form.addEventListener('submit', (evt) => {
    evt.preventDefault();
    // let vid = id.value, url, method;
    let vid = id.value;
    if (vid) {
        url = 'http://127.0.0.1:8000/books/api_category/' + vid + '/';
        method = 'PUT';
    } else {
        url = 'http://127.0.0.1:8000/books/api_category/';
        method = 'POST';
    }
    let data = JSON.stringify({id: vid,nameCategory: name.value});
    productUpdater.open(method, url, true);
    productUpdater.setRequestHeader('Content-Type', 'application/json');
    productUpdater.send(data);
})

Here is my views.py:这是我的 views.py:

@api_view(['GET', 'POST'])
def api_products(request):
    if request.method == 'GET':
        productsAll = CategoryMaskarad.objects.all()
        serializer = CategorySerializer(productsAll, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = CategorySerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET', 'PUT', 'PATCH', 'DELETE'])
def api_rubric_detail(request, pk):
    product = CategoryMaskarad.objects.get(pk=pk)
    if request.method == 'GET':
        serializer = CategorySerializer(product)
        return Response(serializer.data)
    elif request.method == 'PUT' or request.method == 'PATCH':
        serializer = CategorySerializer(product, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'DELETE':
        product.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

Here is my urls.py:这是我的 urls.py:

 path('api_category/<int:pk>/', api_rubric_detail),
 path('api_products/', api_products),
 path('api/drf-auth/', include('rest_framework.urls'))

I added the last path and logged in. In the api interface it became possible to add to the api using the post method, but with the help of js in my html I cant add data.Help me, please我添加了最后一个路径并登录。在api界面中可以使用post方法添加到api,但是在我的html中的js帮助下我无法添加数据。请帮助我

I have this option.我有这个选项。 He is work.I added to js file:他在工作。我在 js 文件中添加了:

name.form.addEventListener('submit', (evt) => {
    evt.preventDefault();
    // let vid = id.value, url, method;
    let vid = id.value, url, method;
    if (vid) {
        url = 'http://127.0.0.1:8000/books/api_category/' + vid + '/';
        method = 'PUT';
    } else {
        url = 'http://127.0.0.1:8000/books/api_category/';
        method = 'POST';
    }
    let data = JSON.stringify({id: vid, nameCategory: name.value});
    productUpdater.open(method, url, true);
    productUpdater.setRequestHeader('Content-Type', 'application/json');
    productUpdater.setRequestHeader('X-CSRFToken', csrftoken);
    productUpdater.send(data);
})

and I added to html file:我添加到 html 文件:

<script>
const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
</script>

when passing data in form to a django rest framework, you do not add the csrf_token tag before forms, rather you pass it as a header when sending api post on your endpoint.将表单中的数据传递给 django rest 框架时,不要在 forms 之前添加 csrf_token 标记,而是在端点上发送 api 后将其作为 header 传递。 Add this line after在后面添加这一行

try adding this function into your codes to get the values of csrftoken尝试将此 function 添加到您的代码中以获取 csrftoken 的值

 let getCookie = (name)=>{ var cookieValue = null; if(document.cookie && document.cookie.== ''){ var cookies = document.cookie;split(";"); for(var i=0. i<cookies;length. i++){ var cookie = cookies[i];trim(). if(cookie,substring(0. name.length+1)===(name+'=')){ cookieValue = decodeURIComponent(cookie.substring(name;length+1)); break; } } } return cookieValue; }

and then change the value you use in x-csrf-token and make it然后更改您在 x-csrf-token 中使用的值并使其成为

productUpdater.setRequestHeader('Content-Type', 'application/json'); productUpdater.setRequestHeader('Content-Type', 'application/json');

productUpdater.setRequestHeader('X-CSRF-Token', getCookie("csrftoken")); productUpdater.setRequestHeader('X-CSRF-Token', getCookie("csrftoken"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 “禁止(CSRF 令牌丢失或不正确。):”使用 Django 和 JS - “Forbidden (CSRF token missing or incorrect.):” using Django and JS 在 Django 中的 ajax POST 期间禁止(CSRF 令牌丢失或不正确。) - Forbidden (CSRF token missing or incorrect.) during ajax POST in Django 禁止(CSRF 令牌丢失或不正确。) | Django 和 AJAX - Forbidden (CSRF token missing or incorrect.) | Django and AJAX Django 和 Axios 禁止访问(CSRF 令牌丢失或不正确。) - Django and Axios Forbidden (CSRF token missing or incorrect.) 如何更正 django 中的以下代码,它给出错误“禁止(CSRF 令牌丢失或不正确。)” - How do I correct the following code in django, It's give an error “Forbidden (CSRF token missing or incorrect.)” (缺少CSRF令牌或不正确。)在Django中使用AJAX - (CSRF token missing or incorrect.) using AJAX in Django 尽管正确发送令牌,Django 服务器仍报告“禁止(CSRF 令牌丢失或不正确。)”? - Django server reporting "Forbidden (CSRF token missing or incorrect.)" despite sending token correctly? 禁止(CSRF令牌丢失或不正确。)-即使已包含 - Forbidden (CSRF token missing or incorrect.) - even though it's included 禁止(CSRF令牌丢失或不正确。)Django如何解决?用我的代码 - Forbidden (CSRF token missing or incorrect.) Django how to solve?WITH MY CODE 用yui设置Django CSRF_TOKEN,但控制台显示“ django.request禁止(CSRF令牌丢失或不正确。)”。 - Set Django CSRF_TOKEN with yui, but console says 'django.request Forbidden (CSRF token missing or incorrect.)'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM