Reputation: 1759
whenever we want to perform a POST
request in django we need to add a csrf_token
. For example if you want to create a form:
<form action="#" method="POST"> {% csrf_token %}
This is pretty simple if you do it in HTML
. However, I want to create forms dynamically using jQuery
. I have the following code:
$div = $('<form/>') // First I am creating the `form` div
.attr("method","POST") //POST method
.attr("action","#");
($div).appendTo('#team_notification_'+index); //Appending it
var $button = $('<button/>') //Creating the buttons
.attr("type","submit")
.attr("name","Accept")
.attr("value", invite[0].pk); //Setting some value
$($button).appendTo($div);
But how can I append the csrf_token
using jQuery?
Thanks
Upvotes: 0
Views: 152
Reputation: 6096
Try something like
var $csrf = $('<input/>')
.attr("type", "hidden")
.attr("name", "csrfmiddlewaretoken")
.attr("value", "{{csrf_token}}");
$($csrf).appendTo($div);
Upvotes: 1