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?