I have created form element dynamically in javascript:
var selectform = document.createElement("form")
I have added other input elements and these attributes to selectform:
submitnselection.setAttribute('type',"submit");
submitnselection.setAttribute('value',"Submit");
submitnselection.setAttribute("name","submitnpage");
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.
This should work:
var inputElem = document.createElement('input');
inputElem.type = 'hidden';
inputElem.name = 'csrfmiddlewaretoken';
inputElem.value = '{{ csrf_token }}';
selectform.appendChild(inputElem);
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!
You can try to append an input field to the form:
// declare an input field
var input = document.createElement('input');
input.type = 'hidden';
input.name = 'csrfmiddlewaretoken';
input.value = '{% csrf_token %}';
// attach field to the form
selectform.appendChild(input);
// submit
If I understand everything, you need to send a csrf token but you don't have any to send to the server from javascript.
From the code in a Django template is very easy to generate a csrf token with the usual {% csrf_token %} Django tag, but this is because the template is being processed in the server to create the final HTML which will be sent to the browser.
When you are in Javascript you can't generate a csrf token so, I think the best solution is creating an invisible tag in the template, probably a hidden input.
<input id="token" type="hidden" value="{% csrf_token %}" ></input>
And when in jQuery get the value with $('#token').attr('value'), I have an example with a jQuery POST method:
token = $('#token').attr('value');
$.post(url, {
'personId': personId,
'csrfmiddlewaretoken': token // This is the important thing
}, function() {}
);
No matter how you do it, you have to send the token with the 'csrfmiddlewaretoken' name and the token value along with the other info you want to send to the server.
I'm editing this with a pure JS solution if you need it. Just say it.