The Django CSRFToken middleware causes the URL to display after sending a "PUT" request to the server, presenting an issue with AJAX

In my current project using Django Python/Javascript, I'm facing an issue with the PUT request. The request is successfully sent to the server by the client, but after that, the page automatically refreshes, exposing the csrf token middleware in the URL. I've tried various solutions such as implementing AJAX, using returning false, adding event.preventDefault(), passing a cookie through the fetch header, utilizing async functions, and incorporating a try and catch syntax. Despite all these efforts, I can't seem to prevent the webpage from refreshing and displaying the csrf_token appended to the URL upon submission.

If anyone has any insights or suggestions on what might be missing here, I would greatly appreciate it! Thank you!

// Define global variables for form submission
var id, upt_prodName, upt_prodPrice, upt_prodDescpt;

// Populate textarea for updating product info
 
 const editProd_view = (response) => {
 
  let prod_id = response.id;
  let edit_name = response.name;
  let edit_price = response.price;
  let edit_descpt = response.description;
 
 
 let prod_idUpt = (document.querySelector("#prod_idUpt").innerHTML = prod_id);
 let new_name = (document.querySelector(
  "#editProdName"
   ).innerHTML = edit_name);
 let new_price = (document.querySelector(
  "#editProdPrice"
   ).innerHTML = edit_price);
 let new_textarea = (document.querySelector(
  "#editProdDescpt"
   ).innerHTML = edit_descpt);
 
 id = prod_id;
 
// Submitting the form to update product info.

 const edit_prod = (document.querySelector(
  "#editProd_form").onsubmit = async () => {
     try {

// Retrieve values from textarea for content update.
     upt_prodName = document.getElementById("editProdName").value;
     new_prodPrice = document.getElementById("editProdPrice").value;
     new_prodDescpt = document.getElementById("editProdDescpt").value;
 
     const res = await fetch(
       `/editProduct/${id}`,
          {
    method: "PUT",
    headers: {
    "Content-Type": "application/json",
    "X-CSRFToken": getCookie("csrftoken"),
    },
    body: JSON.stringify({
      name: upt_prodName,
      description: upt_prodDescpt,
      price: upt_prodPrice,
     }),
    })
    .then((res) => res.json())
    .then((result) => {
console.log("result ->", result);
    });
} catch (err) {
  console.error("err", err);
}

// Prevent reloading once post submission is completed.

 edit_prod.handleForm();
 return false;
 });

return false;
};

Answer №1

In Django, when performing a POST or PUT request, you need to include a CSRF token for delete operations. This is my workaround:

Here's how you can achieve this:

<form>
 <button id="onsubmit" method="{{csrf_token}}">submit</button>
</form>

$(document).on(function() {
   $(document).on('click', '#onsubmit', function() {
      var token = $(this).attr("method")
      const res = await fetch(
       `/editProduct/${id}`,
          {
    method: "PUT",
    headers: {
    "Content-Type": "application/json",
    "X-CSRFToken": token,
    },
    body: JSON.stringify({
      name: upt_prodName,
      description: upt_prodDescpt,
      price: upt_prodPrice,
     }),
    })
    .then((res) => res.json())
    .then((result) => {
console.log("result ->", result);
    });
} catch (err) {
  console.error("err", err);
}
   })
})

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

After using driver.execute_script, the variable results in nil

Attempting to retrieve a lengthy string of URLs separated by commas is proving challenging. The code functions correctly in the console, but when running the script, the ruby variable urls_list remains nil. require 'rubygems' require 'selen ...

Instructions on how to include a conditional click attribute to a hyperlink

Is there a way to make an anchor tag trigger a function only if a specific variable is set? In this scenario, the variable name is assigned the value of "Shnick", so when the link is clicked it should activate the func() method. However, clicking the link ...

Script executing single run only

I'm currently working on a side menu that slides open and closed from the left with the press of a button. I have successfully implemented the CSS and HTML code, but I am facing issues with the JavaScript. The functionality works flawlessly at first: ...

Using React Router to send selected component to parent element

The content of App.js includes the following; render() { return ( <div className="App"> <Navbar /> </div> ) } Meanwhile, in Navbar.js class Navbar extends React.Component { render() { ret ...

(Express JS) What is the correct way to integrate another module into my router? (I am consistently encountering an undefined reference error)

I am currently working on a basic PDF reader application that utilizes the pdf.js library from Mozilla. The user is expected to select a file, after which the website should automatically redirect to the /reader page displaying the PDF. However, I am facin ...

Determine if a certain value is present in a JSON data structure

Exploring the depths of NodeJS, I am utilizing a JSON Object for user validation. JSON content (users.json): { "users": [{ "fname": "Robert", "lname": "Downey Jr.", "password": "ironman" }, { "fname": "Chris", ...

What is the process for generating an array of objects using two separate arrays?

Is there a way to efficiently merge two arrays of varying lengths, with the number of items in each array being dynamically determined? I want to combine these arrays to create finalArray as the output. How can this be achieved? My goal is to append each ...

'jQuery' is not recognized as defined, error no-undef

I am currently working on a file that utilizes jQuery for testing purposes: (function($) { "use strict"; // Start of use strict // Configure tooltips for collapsed side navigation $('.navbar-sidenav [data-toggle="tooltip"]').tooltip({ ...

Error: webpack-cli encountered an unrecognized argument along with a syntax error

Hello, I am currently delving into the realm of prestashop theme development. After setting up my local environment successfully, everything seems to be working fine. My next step is to create a new theme based on the classic default theme. Upon navigat ...

Failure to display alert message upon completion of AJAX request

I am attempting to use AJAX to send data to the database without refreshing the page when a user favorites a message. Even though the data is successfully sent to the DB, the page still reloads and the alert message I want to display is not showing up. Th ...

What is the best method for retrieving a targeted value from an object by using a foreign key relationship in Django?

Hello everyone! I have a table with data and I'm looking to retrieve all SCAD files from the objects of Model3D where the "part_of" attribute is not null and has the same ID as the Model3D. In this case, Model3D represents a 3D printer object that can ...

Hassle with iOS Phonegap selecting multiple lines of text?

For my Phonegap app, I need users to be able to select and modify text inside a p element. The issue arises when trying to select text within the p tag. The text is fetched from my server and displayed as follows: <p style="white-space:pre-wrap">Lo ...

What is the general consensus on combining SWR with Redux - is it considered a best practice?

I am currently incorporating both SWR and Redux into my code. Here is how I'm using them together: const vehiclesStates = useSelector(({ vehiclesStates: state }) => state); // REDUX const response = useFetch("/vehicles/states") // SWR con ...

Avoiding the "urls" format using the onBeforeRequest function

chrome.webRequest.onBeforeRequest.addListener(function(details) { if (localStorage.on == '1') { return {cancel:true}; } }, {urls: ["*://*.domain1.net/*","*://*.domain2.com/*","*://*.domain3.com/*"], types: ["script","xmlhttpreques ...

Using the <script> attribute within the <head> tag without the async or defer attributes

https://i.stack.imgur.com/cRFaR.pngCurious about Reddit's use of the async or defer attribute in the script tag. Are there situations where blocking the parser is necessary? ...

What could be causing my dash/hyphen character to vanish when using JavaScript on my website?

I'm on a mission to swap out spaces with dashes or hyphens in JavaScript. I've managed to write most of the code that inserts dashes after each space between characters (without creating double dashes), but as soon as I add another character, the ...

Is it possible for a d3 chart to render twice in one area if it's rendered in two different places?

When attempting to showcase two distinct d3 pie charts on my webpage within individual mat-cards, they both end up displaying in the svg tag of the first d3 chart in my code. This is what my code looks like: <section class="three"> <! ...

AngularJS combined with MVC is causing an issue where the table fails to refresh following an HTTP post request

When working with an $http.post() call and trying to update an HTML table in the success() callback, I encountered an issue: .success(function (data) { $scope.categories.push(data); }); Here is the HTML code for the table: <tbody> ...

Update the data in Firebase, but revert it back to the original state after a few seconds with the use of "angularFire."

I'm currently working on updating data in the Firebase Realtime Database using Angular and AngularFire. The issue I'm facing is that even though the data changes successfully, it reverts back to the original data after a few seconds. Below is the ...

Navigating through multiple pages with React Native stack navigation

I'm currently in the process of developing a react native app and I'm facing some confusion with regards to page navigation. It appears that there is a glitch in the navigation flow, causing it to skip a page. <NavigationContainer> ...