简体   繁体   中英

Django Form csrf_token

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

Try something like

var $csrf = $('<input/>') 
               .attr("type", "hidden")
               .attr("name", "csrfmiddlewaretoken")
               .attr("value", "{{csrf_token}}");
$($csrf).appendTo($div);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM