You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Django中使用表单外Delete请求遇CSRF_TOKEN验证问题

Fixing CSRF Token Not Found Error in Your Django To-Do App

Hey there! Let's work through this CSRF token issue you're hitting—this is a super common snag when building Django apps with dynamic actions like deleting to-do items, but we can sort it out.

First, let's break down the most likely causes and fixes based on how you're handling the delete action:

1. You're using AJAX for the delete request (not a standard form submit)

If you're using JavaScript to send a POST request when clicking the "×" button, just wrapping your list in a form with {% csrf_token %} won't automatically pass the token to your AJAX call. Browsers only auto-include CSRF tokens for standard form submissions, not AJAX. Here's how to fix this:

Step 1: Grab the CSRF token from your page

You can get it directly from the csrfmiddlewaretoken input that {% csrf_token %} generates:

const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;

Or, if you prefer pulling it from the cookie (Django stores it in a cookie named csrftoken by default):

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();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
const csrftoken = getCookie('csrftoken');

Step 2: Include the token in your AJAX request headers

When sending your POST request, add the X-CSRFToken header:

fetch('/delete-todo/' + todoId, {
    method: 'POST',
    headers: {
        'X-CSRFToken': csrftoken,
        'Content-Type': 'application/json' // Include this if sending JSON data
    },
    // Add your request body here if needed
})
.then(response => response.json())
.then(data => {
    // Handle the response (e.g., remove the to-do item from the DOM)
});

2. Your delete button isn't inside the form with the CSRF token

If you're using a standard form submit for deletion, make sure each "×" button is nested inside its own form (or the parent form you created) so the token is included when the form is submitted. A common pattern for to-do apps is to wrap each delete button in a small, dedicated form:

{% for todo in todo_list %}
    <div class="todo-item">
        <p>{{ todo.description }}</p>
        <!-- Each delete button gets its own form with CSRF token -->
        <form method="POST" action="{% url 'delete_todo' todo.id %}">
            {% csrf_token %}
            <button type="submit" class="delete-btn">×</button>
        </form>
    </div>
{% endfor %}

This ensures that when you click the "×", the form submits with the CSRF token included automatically.

3. Double-check Django's CSRF middleware

Make sure django.middleware.csrf.CsrfViewMiddleware is present in your settings.py under MIDDLEWARE. It should look something like this:

MIDDLEWARE = [
    # ... other middleware ...
    'django.middleware.csrf.CsrfViewMiddleware',
    # ... other middleware ...
]

This middleware is required for Django to enforce CSRF protection—if it's missing, you'll run into token validation errors.

4. Verify your view is set up for CSRF protection

  • For function-based views: If you're not relying on the middleware, add the @csrf_protect decorator to your view:
    from django.views.decorators.csrf import csrf_protect
    
    @csrf_protect
    def delete_todo(request, todo_id):
        # Your delete logic here
    
  • For class-based views: Ensure you're using csrf_protect (either as a decorator or a mixin):
    from django.views.decorators.csrf import csrf_protect
    from django.utils.decorators import method_decorator
    from django.views import View
    
    @method_decorator(csrf_protect, name='dispatch')
    class DeleteTodoView(View):
        # Your view logic here
    

Start with checking whether you're using AJAX or form submissions—this is usually the root cause. Let me know if any of these steps resolve your issue!

内容的提问来源于stack exchange,提问作者Rohan Kandi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:04:49