Answer the question
In order to leave comments, you need to log in
How to pass a JavaScript token for the POST method in Django when updating pages dynamically?
In the latest Django, tokens are provided when transmitting data using the POST method to prevent attacks. Something like:
def main_init ( request ) :
dimention_to_template = {} # словарь, для передачи шаблону
dimention_to_template.update( { 'data': 100 } )
dimention_to_template.update( csrf(request) ) # токен, для метода POST
response = render ( request, "index.html", dimention_to_template )
return response
<form action="get_address" method="post">
{% csrf_token %}
<input type="text" name="addr" value="Город, улица, дом" />
<button type="submit">Найти</button>
</form>
<form id="input_address">
<div id="box">
{% csrf_token %}
<input type="text" name="addr" value="Город, улица, дом" id="address" />
<button type="submit">Найти</button>
</div>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#input_address').submit(function(){
$.ajax({
type: "POST",
url: "get_address",
data: "address="+$("#address").val(),
success: function(html){
$("#box").html(html);
}
});
return false;
});
});
</script>
Answer the question
In order to leave comments, you need to log in
There are a million answers on the Internet. Most often in such cases (i.e. in some external more or less reusable scripts), I stupidly put the token on the main page, then use it simply as a JS variable: dark-barker.blogspot.ru/2013/10/ django-csrftoken-a...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question