The CSRF token is required for this action to be completed

Just recently, I discovered how to set up a web server on a Raspberry Pi using Django. I'm in the process of enhancing it by integrating JS to generate a form every time data is sent. However, I've encountered an error that I haven't been able to resolve yet. Any assistance would be greatly appreciated.

When running the web server, here's the error I come across: view error image here

Below is my HTML code:

<!DOCTYPE html>
<html>
<head>
    <title>blablablai</title>
    <script>
        function sendDirection(direction) {
            const data = new FormData();
            data.append('direction', direction);
            const request = new XMLHttpRequest();
            request.open('POST', '{% url "home" %}');
            request.send(data);
        }
        
        function onMouseDown(direction) {
            sendDirection(direction);
        }
        
        function onMouseUp() {
            sendDirection('stop');
        }
    </script>
</head>
<body>
    <h1>bzzzz....</h1>

    <button type="button" onmousedown="onMouseDown('forward')" onmouseup="onMouseUp()">Forward</button>
    <button type="button" onmousedown="onMouseDown('backward')" onmouseup="onMouseUp()">Backward</button>
    <button type="button" onmousedown="onMouseDown('left')" onmouseup="onMouseUp()">Left</button>
    <button type="button" onmousedown="onMouseDown('right')" onmouseup="onMouseUp()">Right</button>

    <form method="post" action="{% url 'change_speed' %}">
        {% csrf_token %}
        <button type="submit" name="speed" value="25">Speed 25%</button>
        <button type="submit" name="speed" value="50">Speed 50%</button>
        <button type="submit" name="speed" value="75">Speed 75%</button>
        <button type="submit" name="speed" value="100">Speed 100%</button>
    </form>
</body>
</html>

Also, here's a snippet from my views.py file:

from django.shortcuts import render, redirect
import smbus

# Define I2C address
SLAVE_ADDRESS = 0x27

# Initialize I2C bus
bus = smbus.SMBus(1)

# Define motor control functions
def forward():
    bus.write_byte(SLAVE_ADDRESS, ord('f'))

# Other motor control functions omitted for brevity

def change_speed(request):
    if request.method == 'POST':
        speed = request.POST.get('speed')

        # Determine speed level chosen
        if speed == '25':
            speed25()
        elif speed == '50':
            speed50()
        elif speed == '75':
            speed75()
        elif speed == '100':
            speed100()
        return redirect('home')
    else:
        return render(request, 'home.html')

As a beginner in Django, I've consulted the official documentation here to resolve my issue, but to no avail. Any guidance on this matter would be highly appreciated!

Answer №1

The instructions indicate the possibility of configuring a request header. Give this a try:

function setDirection(direction) {
  const data = new FormData();
  data.append('direction', direction);
  const httpRequest = new XMLHttpRequest();
  httpRequest.open('POST', '{% url "home" %}');
  httpRequest.setRequestHeader("X-CSRFToken", document.querySelector('[name=csrfmiddlewaretoken]').value))
  httpRequest.send(data);
}

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

How to remove the horizontal scrollbar from material-ui's Drawer element

My drawer is displaying a horizontal scroll, despite my efforts to prevent it. I've tried adjusting the max-width and width settings in Menu and MenuItems, as well as using box-sizing: border-box. I also attempted setting overflow: hidden on the Drawe ...

How can we avoid animations being interrupted by user interaction?

My webpage has an animation that runs smoothly on desktop, but stops as soon as I interact with the page on a touch device. I have tested this issue on Chrome and Safari on iPad. I'm curious if this behavior is intentional on the part of browser vend ...

Using the HttpPut method in conjunction with a route controller

Hey there, I could really use some assistance. I'm currently attempting to utilize the PUT Method via AJAX in order to send data to a controller for an update operation. Here's my JavaScript and AJAX code: function UpdateProduct() { var id = loc ...

Troubleshooting a 400 Bad Request Error in jQuery Ajax for WordPress Widgets

I am attempting to send information to admin-ajax.php in order to save it as a $_POST variable for handling on the cart page. However, my .ajax function keeps failing. var sendJsonA = {'value':'Data coming from JSON'} var ajaxurl = $ ...

The content located at “http://localhost:3000/public/static/” was restricted because of a mismatch in MIME type (text/html) which triggered the X-Content-Type-Options:nosniff protocol

https://i.stack.imgur.com/7Etn7.png Every time I try to run the server with nodemon, I keep encountering the error mentioned in the title. Below is the code snippet from the JavaScript file: const express = require('express') const path = requir ...

Having trouble choosing a subitem from a dropdown menu in Vuejs?

An example can be found at https://jsfiddle.net/79epsrmw/. However, the issue arises when targeting the item1 sub-menu in VS Code even after assigning a unique id. var app = new Vue({ el: '#app', data: { menuItems: [ ...

Discovering whether a link has been clicked on in a Gmail email can be done by following these steps

I am currently creating an email for a marketing campaign. In this email, there will be a button for users to "save the date" of the upcoming event. I would like to implement a feature that can detect if the email was opened in Gmail after the button is cl ...

Develop a dynamic progress bar with Symfony 2 Framework to display status updates as a task is being executed

Having conducted extensive research and testing, I find myself in a situation where posting this information request is my last resort. Despite numerous attempts, I have been unable to achieve the desired outcome. My goal with Symfony Framework v2.8 is ra ...

If you are having trouble with jQuery AJAX dataType:"json", try using Array instead

Initially, I attempted to send a JavaScript JSON Object to a PHP page but encountered difficulties in doing so. The code snippet below was used for testing: var testobj = { "test1":"test1data", "test2":"test2data", "test3":"test3data" }; alert(testo ...

Issue with activation of onClick event in case/switch statement

Currently working on a JavaScript project to recreate the Fallout terminal game, with one of the main aspects being comparing words selected by the user to those chosen by the computer. The concept of this hacking game is reminiscent of the board game Mas ...

Guide to making type-safe web service requests using Typescript

When utilizing Angular for web service calls, it's important to note that the type of the returned object is not automatically verified. For example, let's say I have a Typescript class named Course: export class Course { constructor( publ ...

Unlocking the AngularJS variable within the template script

My controller code: $scope.totals = totals; In the template, I am able to successfully inject HTML using this code: {{totals}} However, my goal is to access the totals variable in a script within the template. Here's what I attempted: <script& ...

An existing INPUT value can be modified by dynamically adding or subtracting values from SELECT OPTION

I currently have an <input readonly> field that displays the total_price value retrieved from a shopping cart stored in the database table. Moreover, I have included a <select> element with different transport options that can either increase o ...

Error message displayed: MUI Textfield does not support input of decimal values

I have a textfield where users can enter the unit price const [unitPrice, setUnitPrice] = useState(0); <TextField label="Unit Price" variant="outlined" margin="normal" value={unitPrice.toString ...

Is it possible for the useUser() function within the Auth0 nextjs-auth0 library to retrieve user information without relying on cookie data?

The useUser() method by Auth0 is designed to retrieve information about a logged-in user by calling the /api/auth/me endpoint. This triggers the handleAuth() function, which sets up Auth0 (creating a sessionCache instance, etc.) and calls profileHandler(re ...

Getting the image name and extension in an Angular application

Within this block of code, I am working with an image named xyz.abc.jpg. I am able to extract the image extension successfully, but now I need to figure out a way to extract the image name itself without the extension included. Is there a way to achieve ...

I am currently working on a Node.js application generated with express-generator and am experimenting with integrating Primus websocket

Currently in the process of developing a nodejs app using express-generator. I'm facing an issue while trying to integrate the Primus websocket into my application. The issue arises when I do not include app.listen(port) in my app.js file, causing the ...

What is the best way to navigate through an XML document within the DOM of an HTML

I am facing an issue with HTML code. My goal is to navigate through an XML document directly from within the HTML code. Here is the XML code: <?xml version = "1.0"?> <planner> <year value = "2000"> <date month = "7" day = " ...

What is the best way to retrieve the dimensions of a custom pop-up window from the user?

Currently, I am in the process of developing a website that allows users to input width and height parameters within an HTML file. The idea is to use JavaScript to take these user inputs and generate a pop-up window of a custom size based on the values pro ...