Forbidden (CSRF token missing or incorrect) Django error

2024/9/24 7:16:44

I am very new to Django. The name of my project is rango and I have created a URL named '/rango/tagger' that is supposed to send an object.

In my java-script, I have tried to communicate with this route by sending it an ajax request as follows:

function send()
{obj = {content:$("#content").val()};$.post('/rango/tagger',obj,function(data){console.log(data);})
}

I have included the {% csrf_token %} in my template. However, it gives me the error as follows:

Forbidden (CSRF token missing or incorrect.): /rango/tagger
[31/Jan/2016 09:43:29] "POST /rango/tagger HTTP/1.1" 403 2274

My function tagger in views.py is as follows:

def tagger(request):
return render(request,'rango/index.html',RequestContext(request))

And I have also defined it in my URL pattern. I suspect my function tagger returns an incorrect value or data (made the change from HttpResponse(request) to the line above based on other SO solutions).

However, it does not seem to work for me. Where am I wrong?

Answer

The AJAX request must include the csrf, because it's another HTTP request, so please copy this code:

// using jQuery
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 protectionreturn (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({beforeSend: function(xhr, settings) {if (!csrfSafeMethod(settings.type) && !this.crossDomain) {xhr.setRequestHeader("X-CSRFToken", csrftoken);}}
});

After you setup that before sending AJAX request to set the csrf.

source

https://en.xdnf.cn/q/71729.html

Related Q&A

How to update artists in scrollable, matplotlib and multiplot

Im trying to create a scrollable multiplot based on the answer to this question: Creating a scrollable multiplot with pythons pylabLines created using ax.plot() are updating correctly, however Im unabl…

Sending Keys Using Splinter

I want to test an autocomplete box using Splinter. I need to send the down and enter keys through to the browser but Im having trouble doing this. I am currently finding an input box and typing tes int…

Split lists within dataframe column into multiple columns [duplicate]

This question already has answers here:Split a Pandas column of lists into multiple columns(13 answers)Closed 3 years ago.I have a Pandas DataFrame column with multiple lists within a list. Something l…

Drawing with turtle(python) using PyCharm

Im running the latest PyCharm Pro version and trying to run the below code from a scratch file but it doesnt seem to work import turtlewn = turtle.Screen() alex = turtle.Turtle() alex.forward(150) a…

How to adapt my current splash screen to allow other pieces of my code to run in the background?

Currently I have a splash screen in place. However, it does not work as a real splash screen - as it halts the execution of the rest of the code (instead of allowing them to run in the background).This…

Reversed array slice including the first element [duplicate]

This question already has answers here:Python reverse-stride slicing(8 answers)Closed 5 years ago.Lets say I have:>>> a = [1, 2, 3, 4]And I want to get a reversed slice. Lets say I want the 1s…

Problem using py2app with the lxml package

I am trying to use py2app to generate a standalone application from some Python scripts. The Python uses the lxml package, and Ive found that I have to specify this explicitly in the setup.py file that…

How to run TensorFlow on AMD/ATI GPU?

After reading this tutorial https://www.tensorflow.org/guide/using_gpu I checked GPU session on this simple code import numpy as np import matplotlib.pyplot as plt import tensorflow as tfa = tf.constan…

Pure virtual function call

Im using boost.python to make python-modules written in c++. I have some base class with pure virtual functions which I have exported like this:class Base {virtual int getPosition() = 0; };boost::pytho…

Expected String or Unicode when reading JSON with Pandas

I try to read an Openstreetmaps API output JSON string, which is valid.I am using following code:import pandas as pd import requests# Links unten minLat = 50.9549 minLon = 13.55232# Rechts oben maxLat …