How to properly append django csrf_token to form in inline javascript?

I have created form element dynamically in javascript:

var selectform = document.createElement("form")

I have added other input elements and these attributes to selectform:

   selectform.setAttribute("method", "post")
   selectform.setAttribute = ("action", "/test")
   "{% csrf_token %}";

In HTML, adding {% csrf_token %} template tag would work, but in this case of javascript i got 403 forbidden error:

CSRF token missing or incorrect.

I have found some solutions but nothing was working for me, is there any way to add {% csrf_token %} to form with only using Django, Javascript and plain Jquery? Also note that this script is inside html, so i think {% csrf_token %} template tag will work.

Answers 1

  • This should work:

    var inputElem = document.createElement('input');
    inputElem.type = 'hidden'; = 'csrfmiddlewaretoken';
    inputElem.value = '{{ csrf_token }}';

    You see, the csrf_token is nothing more that a string which is the value of a hidden input element of a form. That's all!

Related Articles