What could be causing the error message "CSRF token missing or incorrect" to appear?

I am facing an issue with returning a value from a View function in Django. This particular function is called from a JavaScript code using Ajax, but I'm encountering an error that says 'Forbidden (CSRF token missing or incorrect)'.

JavaScript/Ajax

The Error message

Here's a snippet of the HTML code involved:


    <div align="center" class="input-line">
     <form class="input-form" method="post">{% csrf_token %}
        <input type = "text" id = "ans" class = "form-control" name = "address" placeholder="Type postcode..."><br><br>
        <button id = "homeBtn" class="btn btn-primary">Find info</button><br><br>
     </form>
</div>

The specific View Function causing trouble is as follows:


    def result(request):
        if(request == 'POST'):
           param = request.form['my data']
           this = runAreaReview(param) #This returns a string
           return HttpResponse(this)

Answer ā„–1

Tips for Handling CSRF Tokens

When making post requests using ajax, remember to include the HTTP_X_CSRFTOKEN header with the cookie value csrftoken stored in the browser. For more information, check out this reference guide.

var csrftoken = Cookies.get('csrftoken');
 $.ajax(
     ...
     headers:{"HTTP_X_CSRF_TOKEN":csrftoken}
 );

If you're using a reverse proxy server like nginx, ensure that you also forward this header to the django application.

Bypassing CSRF Verification

If needed, you can disable csrf verification for a specific view by using the @csrf_exempt annotation. Here's a helpful guide on how to implement it.

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def result(request):
    ...

Consider Security Risks

While it's possible to turn off the csrf middleware in settings for non-production projects, this method is not recommended for security purposes. Only use this approach if you are building something for recreational purposes and not for production.

Answer ā„–2

If you happen to stumble upon this discussion, it's important to note that in Django 2.1, the correct HEADER key should be X-CSRFToken. Here is a helpful link for more information: https://docs.djangoproject.com/en/2.1/ref/csrf/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for establishing a real-time connection with a PHP file on a web server using PhoneGap (Android app)

When testing the provided code on a wamp server in localhost, everything runs smoothly. The code calls a php file to connect to a MySql DB and fetch data. Nevertheless, my current goal is to create a mobile app using PhoneGap. The given code resides in an ...

Nuxt has the ability to display the object itself, however, it cannot render its

I am using a directus API to fetch data, which is returned in an array of objects. I can render the array or an object from it, but not when trying to access a property of the object <template> <div class="grid grid-cols-2 gap-6 mt-6&quo ...

How can I code a script to import JSON data into MongoDB database?

I have a JSON file named "data.json" that contains an array of people's names as shown below: "data": [ { { "name":"John", "age":30, } { "name":"Mark", "age":45, } } ] I am ...

Converting Venn diagram code from JavaScript <script> tags to Angular 2: A step-by-step guide

I am struggling to incorporate a Venn diagram into my Angular 2+ project. I followed the code sample provided at - http://jsfiddle.net/johnpham92/h04sknus/ To begin, I executed the following command - npm install venn.js Then I proceeded with impl ...

Troubleshooting the "Request failed with status code 500" error when refreshing a page in a React application

Every time the page is reloaded, an error message pops up saying: Uncaught (in promise) Error: Request failed with status code 500. Here's the code in list.tsx: const [state, setState] = useState([]); const { getRoom } = useRoom(); const fe ...

Show data from an API in an HTML table

I encountered an issue with an API, and despite trying console.log(response.[""0""].body) to view the response in the console, it does not seem to be working. My goal is to extract all the data from the API and display it in a table. Below is my code: ...

Is it possible to retrieve several columns using the pluck method in Underscore.js following the input from the where method, similar to LINQ

var persons = [ {name : "Alice", location : "paris", amount : 5}, {name : "Bob", location : "tokyo", amount : 3}, {name : "Eve", location : "london", amount : 10} ]; var filteredResults=_.pluck(_.where(persons, {location : "paris"}), 'nam ...

Using Firebase with Arrays in Javascript

Currently, my team and I are working on a project using Firebase with Vue.js as the framework. We've come across a challenge regarding creating, updating, and deleting elements in a Firebase cloud document. For instance, within our 'people&apos ...

Navigate to the following section on an HTML page by clicking a button using jQuery

Within my application using Jquery / Javascript, I am looking to implement a specific functionality. I currently have several div elements like the ones below: <div id="div1"></div> <div id="div2"></div> <div id="div3"></ ...

Numerous toggles available for the mobile version

Hey there, I need some help! I have a footer navigation on my desktop website with 3 Ul elements. I want to turn each Ul into a toggle for the mobile version. Can anyone assist me with this? Thanks in advance! <footer class="footer"> <d ...

What is the best way to display a button only when a different element is in focus?

I am working on a feature where each row consists of two text inputs and a button. The goal is to show the button when a user focuses on one of the input fields, and hide it again when they lose focus. I have come up with this solution: const Input = ({inp ...

Encountered an undefined error while trying to read promises

I'm attempting to receive a response from a function in order to trigger another function, but I am not receiving the expected response. I encountered the following error message: "TypeError: Cannot read property 'then' of undefined." In my ...

Connecting Bootstrap Tabs Dropdown to Website LinksIncorporating Bootstrap Tabs Dropdown Menu

Having an issue with my dropdown list in the Twitter Bootstrap tab - it's not responding when clicked. I've checked Stackoverflow for solutions but nothing has worked so far. I even tried removing the data-toggle='tab' attribute. Just ...

Adjust the menu scrollbar position to the right or limit scrolling to within the menu area

$(function() { "use strict"; $(".navbar-toggler").on("click", function() { $(".navbar-toggler").toggleClass("collapsed"); $(".offcanvas-collapse").toggleClass("open"); let menuposition = $("#toggler").offset().left + $("#toggler").width() + ...

Please submit the form to log in with your credentials

Here is the HTML code snippet for a form where users can enter their username and password to log in: <form Name ="form1" Method ="POST" ACTION = "userlogin.php" id="form1"> <div id="main_body" class="full-width"> <label>User ...

Tips for resolving SQLite cookie error code 1555 in Python when using Selenium

I have a piece of code that is designed to open a specific website, log in, and then go to a directed link. It was working perfectly when I tested it individually, but now I need to run multiple instances of it. To achieve this, I simply copy and paste the ...

How to extract and print content within a div element using Selenium and Python

Looking to extract data from a website that has information nested under a specific div tag. Here is an example: <div> id="searchResults" class="multiple-view-elements" <span>name</name> <span>info</name> <span>info< ...

JavaScript: Invoking a nested function within a namespace

script1.js var MyNamespace = {}; MyNamespace.addNewFunction = function(a,b,c) { function doSomething() { // Perform some action here } } script2.js MyNamespace.addNewFunction.doSomething() ?? Iā€™m a bit unsure on how to access the content ...

What could be causing the AJAX http_response_code() to return an incorrect value in this PHP include file? Is it possible that the trailing space at the end is

This issue is perplexing - a seemingly innocuous blank line at the end of a required PHP file in an AJAX POST endpoint, named cursed.php, is causing HTTP response code 500 to fail. Strangely enough, with the blank line present, the status code returned is ...

Having difficulty retrieving the appropriate links while disregarding the irrelevant ones

Recently, I developed a script in python using selenium and BeautifulSoup to extract property details links from a webpage. Due to the dynamic nature of the content, I relied on selenium to fetch the page source. When running the script, it retrieves numer ...