0

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

1

1 Answer 1

1

Try something like

var $csrf = $('<input/>') 
               .attr("type", "hidden")
               .attr("name", "csrfmiddlewaretoken")
               .attr("value", "{{csrf_token}}");
$($csrf).appendTo($div);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.