Error: CSRF token not found or invalid. What is the procedure for transmitting a CSRF token from the frontend to the backend?

In my Django project, I have a task that involves sending a date string from the frontend to the backend. On the frontend, I am utilizing JavaScript's fetch method.

async function getCustomerInDeliveryDate(deliveryDate : String) {
        const response = await fetch('getCustomerInTripDate', {
            method : 'POST',
            headers : {
                'Content-Type' : 'application/json',
            },
            body: JSON.stringify({
                deliveryDate :  deliveryDate
            }),
        });
        return response
    }
    

In the Django backend, I have a basic method set up that currently returns a string to the frontend.

class GetCustomerInTripDate(LoginRequiredMixin, View):
        def post(self, request, *args, **kwargs):
            print('Backend received call from front end!!!!!!!!!!!!!')
            return JsonResponse({'data': ['hello', 'world']}, status = 200)
    

Upon attempting to send data to the backend, I encounter the following error:

Forbidden (CSRF token missing or incorrect.): /staff/getCustomerInTripDate
    

I'm unsure how to include the CSRF token. The information I've found suggests setting credentials as "same-origin", which I've tried but still receive the same error message.

Answer №1

To ensure security, remember to include {% csrf_token %} in your template file.

If you are working with a standard HTML form, place the token inside the form tags.

<form action="/your-name/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit">
</form>

For Ajax requests, the placement of the token does not matter as long as it is included in the POST data.

submitData = {
  
  // other data

  'csrfmiddlewaretoken': $("[name=csrfmiddlewaretoken]").val()
};

$.ajax({
  method: 'post',
  url: 'some_url',
  data: submitData,
  success: function(data){
    // do things
  },
  error: function(event,xhr,settings,errorText){
    // handle errors
  }
});

Answer №2

It appears that the issue you are encountering is related to Cross Site Request Forgery (CSRF)

You can find a more in-depth explanation here https://docs.djangoproject.com/en/4.1/ref/csrf/

To address this problem, consider incorporating {% csrf_token %} protection within your Django templates.

<form action="" method="post">
    {% csrf_token %} <----- INSERT THIS LINE
......all other form elements go here
</form>

If you are not utilizing Django templates, try applying the csrf decorator to your view. Here's a suggested implementation:

from django.utils.decorators import method_decorator<----- ADD THIS
    
@method_decorator(csrf_exempt, name='dispatch')<----- INCLUDE THIS
class GetCustomerInTripDate(LoginRequiredMixin, View):
    def post(self, request, *args, **kwargs):
        print('Backend received call from front end!!!!!!!!!!!!!')
        return JsonResponse({'data': ['hello', 'world']}, status = 200)

This solution should hopefully resolve the issue. Let me know if you need further assistance. Best regards.

Answer №3

By default, the CSRF token is stored as a cookie. To access it, use JavaScript to retrieve the cookie and then send the token.

Alternatively, you have the option of creating a restful endpoint for this purpose.

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

box tick does not alter appearance

I've been struggling with this seemingly simple issue for an hour now. I have a radio button set up with two buttons: <input class="form-control icheck" id="cash_prize" name="cash_prize" type="radio" value="1" style="position: absolute; opacity: 0 ...

Exporting a module with Node.js is a crucial aspect of building

Within my custom module, I have successfully set up an export function. module.exports = function(callback) { var request = require("request") var url = "http://sheetsu.com/apis/94dc0db4" request({ url: url, json: true }, ...

What is the reason behind jshint issuing an alert specifically for the lastSelectedRow being

Upon pasting the code below into jshint.com, an error is generated: Read only in reference to line: lastSelectedRow = 1; I am curious as to why this error occurs and how it can be remedied. Interestingly, jslint does not return this error. /*global la ...

Is it possible for a conditional type in TypeScript to be based on its own value?

Is it possible to use this type in TypeScript? type Person = { who: string; } type Person = Person.who === "me" ? Person & Me : Person; ...

Why is the imported package not being recognized in the namespace declaration of my Node.js TypeScript file?

Currently, I am utilizing the WebStorm IDE developed by JetBrains to modify a TypeScript file within a Node.js v8.6.0 project. The JavaScript version set for this project is JSX Harmony. In the beginning of the TypeScript source file, there is an import st ...

Is there a way to give a ReactJS button a pressed appearance when a key is pressed?

I recently developed a Drum Machine using ReactJS, but I'm facing an issue with making the buttons look like they've been clicked when I press the corresponding key. I came across a similar query on this site, however, I'm having trouble imp ...

Is it possible to have 1 million links on a single webpage?

Would the performance suffer if I were to fetch 1 million link elements and add them to the DOM? I am looking to create a navigation list at the top of my website, similar to what Apple has on their site where you can scroll left or right using your keybo ...

Information derived from a provided URL

I am currently developing a Spotify stats app, and I am facing an issue with creating a context to store the token provided by the app in the URL when a user logs in. TokenContext.js: import React, { useEffect, useState } from "react"; // token ...

Show only child elements of a specific type within the parent div

Looking to identify divs with the class 'test' that contain only buttons in their child nodes. This is the HTML code that needs to be filtered. <div class="test"> <div> <button> <span>Button 1</span></butto ...

Creating an overlay button within various containing divs requires setting the position of the button

Tips for overlaying a button on each HTML element with the class WSEDIT. My approach involves using a JavaScript loop to identify elements with the CSS class WSEDIT, dynamically create a button within them, and prepend this button to each element. Below ...

I possess a pair of items that require merging together while combining any overlapping key values in their properties

I have a scenario where I need to merge two objects and concatenate strings if they have the same key. obj1 = { name: 'John', address: 'Cairo' } obj2 = { num : '1', address: 'Egypt' } After merging, the r ...

Steps for updating the property "project_id" within a nested JSON array to "project_name"

Issue: [ { "project_id": 1, "project_name": "CDP", "role": "PL" }, { "project_id": 2, "project_name": "Admincer", "role": "PM" }, I am trying to extract the "project_id" property from the above JSON array and add it to another array using a specific ...

Unable to interpret Python/Django-generated JSON object on client side

I'm encountering an issue while passing a data object from a Python/Django application to the frontend using AJAX in JSON format. Despite everything appearing to be functioning correctly, I am unable to properly parse the JSON object within JavaScript ...

Delete one item from a group of objects[]

In my TypeScript code, I have a declared object like this: public profileDataSource: { Value: string, Key: number }[]; This results in an object structure that looks similar to the following: 0: Object {Value: "<Select Profile>", Key: null} ...

Is there a way to eliminate the blue border from a Material React Modal?

I am currently using the React Material Modal and noticed that in the demo examples, there is a blue border when the modal is opened. Is there a way to remove this blue border? I have tried setting the disableAutoFocus property to "true" in the Modal Api ...

Create specification for the properties of the child component

I am interested in working with the props of a parent element's children and validating those props. Can I achieve this using prop-types? export default function MyComponent(props) { return ( <div> {React.Children.map(props.chil ...

Getting the value returned by http.request in an app.get method using express.js

When attempting to deliver data from an API on another domain using app.get, I am able to write the data to the console successfully. However, the data is not showing up on the page ('~/restresults'). This is the current code I have: app.get(&a ...

What is causing the malfunction in this straightforward attrTween demonstration?

Seeking to grasp the concept of attrTween, I am exploring how to make a square move using this method instead of the simpler attr approach. Despite no errors being displayed in the console, the following example does not produce any visible results, leavin ...

How to prioritize indices when querying multiple indexes in Elasticsearch?

Utilizing the Elasticsearch multi index API, I am able to query across multiple indices. However, it is important for me to prioritize my queries. As an illustration, when querying in the indices index1 and index2, the syntax would look like: /index1,ind ...

Tips for managing onClick events within a conditional component

I am currently attempting to implement an onClick event on the data that I have selected from the AsyncTypeahead. My goal is to pass a callback function to the Problem component, which will only render if an item has been selected. However, after selecting ...