Django 1.9.2 + jQuery + POST - Error 403 - missing or incorrect CSRF token

advertisements

i'm new to django, I'm trying to fire simple function from views.py by clicking button on webpage. That's what I've done:

HTML:

<form method="post">{% csrf_token %}
<button type="submit" class="btn btn-circle btn-primary btn-xl" id="add_address_button"><i class="fa fa-check"></i></button>
</form>

    $('#add_address_button').click( function() {
        $.post("adres/add_address_button_action/", function () {
            alert('OK');
        });
    });

urls.py

url(r'^adres/add_address_button_action/$',views.add_address_button_action, name = 'add_address_button_action'),

views.py

def add_address_button_action(request):
    adres = get_object_or_404(Adres, id =2)
    return render(request, 'serwis/address_detail.html', RequestContext(request,  {'address_detail_zmienna': adres}))

Information from terminal:

Forbidden (CSRF token missing or incorrect.): /adres/add_address_button_action/
...
"POST /adres/add_address_button_action/ HTTP/1.1" 403 2274

I was trying different return in views.py:

return render_to_response('serwis/address_detail.html', RequestContext(request, {'address_detail_zmienna': adres}))
return redirect('serwis/address_detail.html', {'address_detail_zmienna': adres})

But none of them works.

I would be very grateful if someone could help me figure that out. I've read lots of topics regarding this issue, but most of them are out dated - and didn't help.

Kind regards


It looks like you aren't passing the CSRF token to the server. See https://docs.djangoproject.com/en/1.9/ref/csrf/#how-to-use-it.

You need to either pre-configure your jQuery to pass the csrf token in the header of every AJAX request you make, or you need to explicitly pass the CSRF token as data to the $.post() function.

Detailed code is available in the above linked documentation.