S
S
Sergey Eremin2014-10-14 18:49:03
JavaScript
Sergey Eremin, 2014-10-14 18:49:03

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

Accordingly, in the template we write something like:
<form  action="get_address" method="post">
    {% csrf_token %}
    <input type="text" name="addr" value="Город, улица, дом" />
    <button type="submit">Найти</button>
</form>

And everything works.
But if the "submit" event in the form handles JavaScript (for example, if you need a dynamic page update), then the token transfer does not occur. What is causing the 403 error. That is, for example, if in our template:
<form id="input_address">
    <div id="box">
        {% csrf_token %}
        <input type="text" name="addr" value="Город, улица, дом" id="address" />
        <button type="submit">Найти</button>
    </div>
</form>

And there is a script that provides submit and reloads the content in the "box" block:
<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>

Then, of course, the token is not sent and an error 403 occurs. The task is to send the token via JavaScript / But how to do it? After all, it is formed by Django ... How to ask him what is changed in the token and how this token is actually called names?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
barker, 2014-10-14
@Sergei_Erjemin

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...

V
Valentine, 2014-10-14
@vvpoloskin

Because they do either
a) data = form.serialize() if we are talking about jquery
b) as it is written in the django manual in the general case
c) they themselves take values ​​from all form inputs in the most general case

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question