Whenever a form is generated dynamically, it consistently encounters a 403 forbidden error when attempting to make a POST request

I am encountering an issue with editing text posts on my website. Whenever I click the edit button, a form is dynamically created to replace the div element. I have set up a POST api in Django to handle the submission of this form and edit the existing post. However, I keep receiving a 403 error when making the POST request. Initially, I thought that the absence of a CSRF token might be the cause of the problem. As a result, I made changes to my JavaScript code as shown below:

                    //form create
                    const post_content_element = post.querySelector('div .text-content');
                    const post_content = post_content_element.innerHTML;

                    let edit_form = document.createElement('form');

                    // Here I added the csrf token as a hidden input 
                    let inputElem = document.createElement('input');
                    inputElem.type = 'hidden';
                    inputElem.name = 'csrfmiddlewaretoken';
                    inputElem.value = '{{ csrf_token }}';
                    edit_form.appendChild(inputElem);

                    edit_form.setAttribute('id', 'edit-form');
                    edit_form.setAttribute('method', 'POST');

                    let text_content = document.createElement('input');
                    text_content.setAttribute('type', 'textarea');
                    text_content.setAttribute('id', 'edit-content');
                    text_content.value = post_content;

                    let submit = document.createElement('input');
                    submit.setAttribute('type', 'submit');
                    submit.setAttribute('id', 'edit-submit');

                    edit_form.appendChild(text_content);
                    edit_form.appendChild(submit);

Despite these modifications, the issue persists with the 403 forbidden response. The structure of my api is as follows:

@api_view(['POST'])
def edit_post(request):
    if request.method == "POST":
        # do something
        return Response(status=status.HTTP_201_CREATED)

I should also mention that I am utilizing my User(AbstractUser) model for authentication. At this point, I am running out of ideas. What other factors could potentially be causing this problem?

Answer №1

My issue was resolved after consulting this helpful resource: https://docs.djangoproject.com/en/1.11/ref/csrf/#ajax

I found the getCookie function outlined on the above mentioned page very useful.

function getCookie(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;}

Following that, I implemented the POST request along with X-CSRFToken header as demonstrated below-

fetch(window.location.origin.concat('<url>'), {
                            method:'POST',

                            credentials: 'same-origin',
                            headers: {
                                "Content-Type": "application/json",
                                "X-CSRFToken": getCookie("csrftoken")
                            },
                           body: <whatever body you have>
                           })

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

Issue encountered when attempting to serve JSON response using Node.js, express, and MongoDB after the initial response

I have been experimenting with creating simple RESTful APIs using Node.js, Express, and MongoDB. For this purpose, I am utilizing the Node.js-MongoDB driver in conjunction with the Express framework. const MongoClient = require("mongodb").MongoClient cons ...

Looking for a discreet JavaScript-based text editor with advanced features?

Our CMS has been using the now-unsupported RichTextBox control for a while, and we want to find a lighter-weight alternative with better cross-browser support. Initially, we were considering different ASP.NET components, but I am starting to think that an ...

Having an issue with button onClick functionality not working in Javascript

Simple enough. I am struggling to get my button to generate the necessary input upon clicking. The fields should populate where the "household" class is located. I am limited to editing only Javascript and not HTML. Any suggestions? HTML: <ol ...

Transform a group of objects in Typescript into a new object with a modified structure

Struggling to figure out how to modify the return value of reduce without resorting to clunky type assertions. Take this snippet for example: const list: Array<Record<string, string | number>> = [ { resourceName: "a", usage: ...

Tips for managing erroneous data in csv files using Node.js

I am currently working on an application that parses csv files using the csv module. It is functioning well, but I am facing a problem where if there is a bad row in the csv file, the entire process fails. Is there a way to skip bad rows and continue stre ...

Issues observed when integrating Axios custom instance with Next.js

Initially, I created a custom axios instance with a baseURL and exported it as shown below: import axios from 'axios'; const instance = axios.create({ baseURL: process.env.BACKEND_URL, }); instance.defaults.headers.common['Authorization& ...

The API has been triggered twice

I am currently working on a React component where I have implemented an API call using the useEffect hook with an empty dependency array. However, I noticed that the API is being called twice and I can't seem to find the reason behind it. import { use ...

When utilised within the same function, JSON values in JavaScript can yield varying results

Recently, I've been grappling with a JavaScript issue that involves fetching JSON values as data-attributes to populate a modal. This task sounds simple enough, but as a newcomer to this field, I find myself facing challenges. The main goal is to ite ...

What is the best way to implement a toggle feature for a single image within a div element that contains multiple images when clicked?

I am facing an issue where I have multiple images stacked on top of each other. When one of the images is clicked, I want a toggle function to activate that changes the opacity of the top image to 0, revealing the image underneath. However, every time I cl ...

Advancement of a grunt chore within a digital platform

After constructing an app with grunt, I am now in the process of developing a web interface using node and angular to interact with this app. One feature I have implemented is a button that triggers a grunt task using childProcess in NodeJS: child_process ...

Setting up a Django development environment without the need for installation - a step-by-step guide

Being a student, I have encountered restrictions set by the lab staff that prevent us from installing software on the machines or to our profiles. I am interested in developing a Django application in a contained environment. I have downloaded the Django ...

What is the process for transferring selections between two select elements in aurelia?

I am attempting to transfer certain choices from select1 to select2 when a button is clicked. Below is my HTML code: <p> <select id="select1" size="10" style="width: 25%" multiple> <option value="purple">Purple</option> &l ...

Utilizing browser's local storage to dynamically update text in buttons and panels

In my file, I have the following code snippet (I've removed other irrelevant code) <div data-role="panel" id="loc_panel"> <h2>Panel Header</h2> <p>info about this stop</p> </div> <!-- /panel --> < ...

Error: Attempting to access 'input_date' property of null object resulted in an uncaught type error

I am attempting to implement pagination for a data table using AJAX to refresh the table without having to reload the entire page. However, I am encountering an issue where the input_date is being considered null even though it should not be. Below is the ...

JavaScript function for validating CGPA or GPA fields

I am encountering issues with JavaScript validation in ASP.NET. The validation seems simple, but for some reason, it is not functioning properly. Below is the code that I have tried: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.as ...

JavaScript - Image style alterations are not operating as expected

Let me break it down for you: onmouseover="imageOn(bg-index);" onmouseout="imageOff(bg-index);" I've got these two attributes set on a table tagged with ID table-title. These functions are included in an external JS file: If the name is 'bg-i ...

Transferring data from one HTML element to another using Angular [Ionic]

My project involves utilizing an ionic slide box to display a series of images within it. <ion-slide-box> <!-- I am looping through the images based on the image count --> <ion-slide ng-repeat="n in [].constructor(imageCount) track by $in ...

JavaScript: Update Div Background Automatically

My website has an advertisement section that works fine for most users. However, if a user has an ad-blocker enabled, the advertisement doesn't display and instead, an empty area appears on the site. To address this issue, I plan to add a background ...

Should tokens be sent via POST request or stored in a cookie?

I have a single-page Node.js Facebook Canvas App. Whenever a user interacts with the app, it triggers an AJAX POST request to my Node.js HTTPS server, which then returns the result. Now, I am looking for a way to send a user token that I generate from the ...

What is the best way to detect a specific button press from an external component?

I need to integrate an external component written in Vue.js that contains multiple buttons. How can I specifically target and capture the click event of a particular button called firstButtonClick() within this external component? Here is how the External ...