Django does not retrieve data using fetch()

I am utilizing the fetch() method to send an ajax request to my server. However, when I use request.POST, it returns an empty QueryDict instead of my actual data which is returned by request.body. Can anyone help me figure out what I'm doing wrong?

Below is a snippet of my JavaScript code:

fetch(url, {
            method: "post",
            credentials: 'same-origin',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'X-CSRFToken': csrftoken,
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify(data)
        })
            .then(async res => ({
                status: res.status,
                body: await res.json(),
                isOk: res.ok
            }))

Answer №1

If you are sending JSON data, using request.POST is not appropriate as it is intended for form data. In this case, the QueryDict will be empty and request.POST should remain empty as well.

Answer №2

It seems like the information you're looking for can be found in the official documentation: specifically, the POST method only includes form data. Files and other types of non-form data are located in the FILE and body attributes.

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

What is the best way to obtain the present date in Nuxt directly from the server?

While conducting code tests, I realized that I required the current time from the server to run the tests effectively. In JavaScript, you can easily obtain the current date on the client side using the command: new Date();. However, when working with Nuxt ...

{% How to use something in Django: A comprehensive tutorial %}

The Django tutorial (part 3) includes the template syntax displayed below: {% if latest_poll_list %} <ul> {% for poll in latest_poll_list %} <li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li> {% endf ...

Is the on.click event fired before the ajax request is made?

Having two events, the second one initiates an Ajax call. When a click creates an input in the <td>, it gets replaced by the success event afterwards - ensuring that the input is correct upon blur. $(document).on("click","#"+table_id+" td",function( ...

Utilizing an external link to dynamically modify the zoom level of a Google map

I've been struggling for hours to adjust the zoom level of a Google map using an onClick JavaScript function. It seems like my variable "map" is inside the initialize function of the map, which might be causing it not to work, but I'm not complet ...

Error: The function openCity() has not been defined

I'm currently working on creating a form that will allow me to store images into a PostgreSQL database. The database contains a single table with two fields: ID and IMG, which is of type bytea. The page has 2 tabs, and I have a function called 'o ...

Algorithm for detecting collisions in Javascript

I am looking to implement a collision detection function in JavaScript for canvas. Specifically, I have coin and piggy bank objects and want to create a function that triggers the disappearance of a coin object when it comes into contact with a piggy bank. ...

Transferring extra data from jQuery autocomplete to a PHP script

Hey there! I'm wondering if it's possible to pass extra parameters from jQuery autocomplete to a PHP page, which would then use them to query a database and return the results. While I know how to send the typed term from the input box, I'd ...

How to Showcase a Circular Shape within an SVG Using D3.js

I've been working on my Angular app and have made some progress. However, I'm having trouble getting a circle to show up on the SVG. Can anyone help me figure out what I'm doing wrong? svg: any; margin = 50; width = 350 - (this.margin ...

How to display a name in an iframe using React

When I retrieve the movie name in React, it appears correctly as {movie.name} / {movie.enname} ({years}) . However, when I try to display this name within an iframe window at https://example.com/movie/{movie.name}, it does not show up properly. Here is th ...

What should be the correct format for the date/time in Django if I am getting the error "AttributeError: 'unicode' object has no attribute 'year'?"

I encountered the 'unicode' object has no attribute 'year' error when using the timesince filter in Django. The filter was functioning properly with strings like "2013-06-20". However, after updating the string to include a time element ...

Modify data source with AngularJS when clicking a button

I have a webpage with a controller called 'listCtrl' that fetches data from "http://data.com/?region=north". app.controller('listCtrl', function ($scope, $http) { $http.get("http://data.com/?region=north").success(function (data) { ...

Utilize JavaScript to Trigger AJAX HoverMenuExtender in .NET

Within my C# web application, I am attempting to trigger an Ajax HoverMenuExtender using JavaScript, rather than relying on hovering over a designated control. When I set the TargetControlID of the HoverMenuExtender to a control on the page and hover ove ...

Adjust the properties within the component's styles using Angular 2

In this project, the objective is to dynamically change the background-color based on different routes. The goal is to display a specific color for UpcomingComponent while keeping the background-color consistent for all other routes. The approach involves ...

The error message states that the property "user" is not found in the type "Session & Partial<SessionData>"

I recently had a javascript code that I'm now attempting to convert into typescript route.get('/order', async(req,res) => { var sessionData = req.session; if(typeof sessionData.user === 'undefined') { ...

Tips for creating a TypeScript-compatible redux state tree with static typing and immutability:

One remarkable feature of TypeScript + Redux is the ability to define a statically typed immutable state tree in the following manner: interface StateTree { readonly subState1: SubState1; readonly subState2: SubState2; ...

Comparison between setTimeout for this.state and useState

When working with a class component, the code looks like this: setTimeout(() => console.log(this.state.count), 5000); Whereas when using hooks: const [count, setCount] = useState(0); setTimeout(() => console.log(count), 5000); If the setTimeout fun ...

What is the process for including a new item in the p-breadcrumb list?

Having trouble getting my code to add a new item to the p-breadcrumb list on click. Any assistance would be greatly appreciated. Thank you in advance! Check out the live demo here ngOnInit() { this.items = [ {label: 'Computer'}, ...

Step-by-step guide on replicating a website along with its CSS styles and scripts

I've been exploring the idea of cloning a webpage, such as Instagram's login page, along with its CSS elements and JavaScript, to use locally. Basically, I want to duplicate the login page and host it on my test server in a way that allows it to ...

Automate the detection of a connected device via USB on a NodeJS server

I created a web interface for a colorimeter by using a NodeJS server that can read USB serial inputs through the serialport npm library. This information is then sent to a local web page. The colorimeter consists of a circuit with a microcontroller that is ...

Tips for effectively handling unique properties of a React component (such as Redux integration and custom CSS) when sharing through NPM distribution

Question: How can custom Redux containers and CSS be effectively managed with NPM? It can be challenging to handle these custom files through traditional package distribution platforms like NPM, especially when they need to be edited in various projects. ...