CSRF verification does not function properly when the script is placed in the static directory

Code Snippet:

   $('.delete').click(function() {  
          if (confirm("Are you sure you want to delete?")) {      
          var csrf_token = $("#csrf_token").val();    
          $.ajax({ // performing an AJAX call...
            data:{
                csrfmiddlewaretoken: ('{{csrf_token}}'),
                delete:true
            },
            type:'POST',
            url: '/feed_list/', 
            cache:false,
            success: function() { 
                window.location.href = window.location;
            }
        });
        return false;
      }
    });

In this JavaScript function, I am calling a method in views.py that performs a delete function. The delete function is functioning properly, however my issue lies in having this JavaScript function on the current HTML page. When attempting to move this function to a static folder -> scripts -> custom.js, it results in a 403 error page with the message

CSRF verification failed. Request aborted.
, although I am passing the CSRF token in both the form and the JavaScript. I am seeking suggestions on how to resolve this dilemma.

Answer №1

Unfortunately, the django server is not capable of rendering js files which means your current solution will not work.

To resolve this issue, you can take the following steps:

First, add a jquery plugin by visiting: http://plugins.jquery.com/cookie/

Then, in your js file, use the code snippet below to retrieve the csrf token:

csrfmiddlewaretoken: $.cookie('csrftoken'),

Answer №2

Ensure that you have set the csrf_token and include it in your ajax request:

data:{
            csrfmiddlewaretoken: csrf_token,
            delete:true
        }

If you are unsure about the input format, I usually define token like this:

token = $('input[name="csrfmiddlewaretoken"]').val()

In the base template, make sure to include {% csrf_token %} which generates the following HTML code:

<input type="hidden" name="csrfmiddlewaretoken" value="your_token">

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

Creating user accounts in Django

Currently working on developing a new social media application, my goal is to establish users without relying on the user creation form in order to construct my own customized form. To achieve this, I am utilizing the User.objects.create_user() function. ...

AJAX request encounters error when trying to send file, receiving a 'blob' error message

I've been struggling with an AJAX request that is supposed to send a file to my controller, where it should be read and then a sorted array returned to the front-end. Unfortunately, I keep getting stuck on an error related to a 'blob' not be ...

Transfer the values of two divs into a unified output div

I am working on a task that involves two text boxes, one with an id and the other with a class. The goal is to copy the values from both text boxes into a single div when a button is clicked. So far, I have made an attempt at this but only the value from t ...

Troubleshooting TextField malfunctioning after button click within Dialog on Material UI

My main objective is to focus on a Material UI TextField after closing a Dialog by clicking a button inside the Dialog. The code snippet below successfully accomplishes this task when triggered from a button that is not within a dialog component: focusOn ...

Generating Bootstrap carousel items dynamically using JavaScript

One of my recent achievements includes creating a webpage that displays a list of loaded data, some of which contain YouTube links. I am currently facing a challenge in trying to showcase these videos in a bootstrap carousel due to the complexity of integ ...

Transform a fabricjs canvas into a base64 encoded image

I am attempting to transmit a canvas as an image to my server in base64 format. While Fabricjs provides options such as canvas.toSVG() or canvas.toDataURL({format: 'image/png'}) to convert the canvas to an image, the output I see in my console ap ...

Enhance your viewing experience with the Zoom feature that activates when

I recently noticed on that I am able to zoom/enlarge a photo by clicking on it. Is there a way for me to incorporate this feature without purchasing the entire theme? While I understand the theme is designed for purchase, I only need this specific functi ...

Encountering a NoSuchElementException when transitioning from frame[0] to window[1] in Firefox GeckoDriver using Selenium with Python

Encountered an issue with the Firefox GeckoDriver browser where I receive an error stating `element not found`. The problem arises when I navigate from window[1] to frame[0], back to window[1], and then attempt to click the close frame button. I prefer u ...

Managing styles and scripts in Asp.Net MVC: A guide to efficient organization

Currently, I am utilizing asp.net mvc 2.0 in my projects and appreciate its design and functionality. However, I find that it lacks proper support for applications with a significant amount of styles and scripts. To address this issue, I implement areas, ...

Is there a way to add to a list using the example provided and display the result as well

Here is the given information: data=[{"id":1,"name":"vikash","roll":39},{"id":2,"name":"kumar","roll":3}] data2=[{"hobby":"football","food":&quo ...

Is there a way to insert a row into a datatable without needing to perform an Ajax reload or using the

When using row.add(…) on a datatable, I encounter an issue where it refreshes via an ajax call when draw() is activated. This leads to the new row not being visible because the data is reloaded from the database. The UX flow behind this scenario is as f ...

I continue to encounter an error every time I attempt to place an HTML nested div on a separate line

When I structure the HTML like this, I don't encounter any errors: <div class="game-card"><div class="flipped"></div></div> However, if I format it differently, I receive an error message saying - Cannot set property 'vi ...

Attempting to make a slightly bigger than usual AXIOS.post request to a .NET Web API

When attempting to perform an AXIOS.post in a Vue.JS application, the process fails when exceeding about 1500 characters. Instead of reaching the Web API, it goes directly to the error area. Typically, this function calls a .Net Web API that generates a MS ...

Managing numerous asynchronous calls using jQuery

I am facing an issue with the tab structure on my website. When clicking on each tab, an AJAX call is made to a unique URL. However, when I click on consecutive tabs, the AJAX call results in an error instead of success. Only the tab that is loaded ini ...

Issue with npm version: 'find_dp0' is not a valid command

Hello, I have a small node application and encountered an issue while running a test. The error message displayed is as follows: 'find_dp0' is not recognized as an internal or external command, operable program or batch file. It seems to be re ...

Exploring Django REST framework's functionality for interacting with nested data through GET and POST requests

Based on this particular model, each individual user possesses multiple albums, and each album contains various tracks. I am seeking guidance on how to enable a user to fetch and add tracks exclusively to the albums they own. Which serializer should I uti ...

Retrieving row and column values from an 81-element indexed array

I am working with an indexed JavaScript array that contains exactly 81 elements. These elements will form a 9x9 grid, similar to a Sudoku puzzle. Right now, I am trying to figure out the most efficient way to extract row and column values from this array. ...

what causes request.GET.get() to result in "None" and why is the value of the html element not displayed in the URL

Homepage <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>HELLO</title> </head> <body> <for ...

Can someone please help me understand why my CSS transform scale isn't functioning properly?

I've developed a JavaScript function that enlarges a button and then smoothly shrinks it back to its original size. The function successfully changes the color of the button to blue, but for some reason, it's not working with the transform prope ...

Limit the vertical movement in Vue drag and drop operations

Currently, I am working on a project that involves implementing drag-and-drop functionality using vue-draggable. You can find more information about it here: https://github.com/SortableJS/Vue.Draggable. I am facing an issue where the height of the element ...