Form created dynamically always gets 403 forbidden on a django rest framework api POST

  csrf, django, javascript

I have multiple text posts on my website. On clicking the edit button I dynamically create a form replacing the div to a form element. I have my POST api set up on the django side to get this form submit and edit the existing post. But my POST request always gets 403. First i assumed not having a csrf token is causing the problem. So i edited my js code to this-

                    //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';
           = 'csrfmiddlewaretoken';
                    inputElem.value = '{{ csrf_token }}';

                    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');


still it gets 403 forbidden. My api looks like this-

def edit_post(request):
    if request.method == "POST":
        # do something
        return Response(status=status.HTTP_201_CREATED)

Please note I am using my User(AbstractUser) model for authentication. I am out of ideas. What could be the other reasons for this problem?

Source: Ask Javascript Questions