添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams
$(".btnApplyConfig").click(function(){
    var token = $("input[name=csrfmiddlewaretoken]").val();
    // Some other vars I'm sending properly
    console.log('token: '+token); //printing correctly
    $("#"+frm).submit(function(e){
        e.preventDefault();
        console.log('Post method via ajax');
        $.ajax({
            url: '/ajax/validate_config',
            type: 'POST',
            data: {
                'token': token,
                //and other stuff I'm sending properly
            dataType: 'json',

my Django view:

def validate_config(request):
    token = request.GET.get('token', None)
    #some other vars I've sent ok with ajax
    data = {
        #some vars
        'token': token,
    if request.method == 'POST':
        item = MyClass.objects.filter(my_keyword=my_filter_values).update(my_ajax_values)
    return JsonResponse(data)

All the data is being processed properly, the only problem for me is that I'm getting the following error:

Forbidden (CSRF token missing or incorrect.): /ajax/validate_config/

I've put some prints in view in order to check if vars are being sent properly, and yes they are. How could I handle it? I checked some tutorials but I couldn't find a solution so far.

A very simpler way

let cookie = document.cookie
let csrfToken = cookie.substring(cookie.indexOf('=') + 1)
$.ajax({
         url: 'url/path',
         type: 'POST',
         headers: {
           'X-CSRFToken': csrfToken

You can use this. You don't have to put anything in your view for it. It will automatically find it.

$.ajax({
  url: ,
  type: "POST",
  data: {
    'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
    // plus other data
  dataType: 'json',
  success: ,

You probably also want to add if request.is_ajax() to your view.

Where exactly I have to put ""if request.is_ajax()"", I already have "if request.method == POST"? – Lord-shiv Sep 13, 2021 at 14:22 @Lord-shiv if request.method == "POST" and request.is_ajax():. request.is_ajax() will prevent it from running the code if it isn't an AJAX request. – Carl Brubaker Sep 13, 2021 at 18:53

This was the solution that worked for me in this case:

Added this code before the Ajax code:

function 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 = jQuery.trim(cookies[i]);
            // 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;
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.