X
X
xakslim2019-11-07 08:35:16
Django
xakslim, 2019-11-07 08:35:16

How to pass CSRF authentication?

All the best )) Task for educational purposes: The page displays a list of services, when you click on one of the services, detailed information about the service appears below. I want to implement this using ajax, I just started to study and when I try to send data I get an error - 403 csrf.

views.py
import json

from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from django.views.decorators.http import require_POST


@csrf_exempt
@require_POST
def service_process(request, lang):
    try:
        data = request.POST
    except ValueError:
        data = {}
    return HttpResponse(json.dumps(data), content_type='application/json')


urls.py
from django.conf.urls import re_path

from pages import views


app_name = 'pages'
urlpatterns = (
    re_path(
        r'^(?P<lang>\w{2})/ajax-test/$',
        views.service_process, name='ajax_test'
    ),
)

main.js
function ajaxTest(data, callback) {

  var url = '/' + $('body').attr('data-lang') + '/ajax-test/';

  $.ajax({
    url: url,
    data: data,
    dataType: 'json',
    type: 'POST',
    timeout: 300000,
    success: function (data) {
      console.log(data);
    },
    error: function (jqXHR, textStatus) {
      console.log(textStatus + ' ' + jqXHR.status + ': ' + jqXHR.statusText);
    }
  });
}

$('.service-title').on('click', function () {
  ajaxTest({'service': $(this).text()})
});

page.html (шаблонизатор jinja2)

{%- extends 'layouts/base.html' -%}
{%- block PAGE_TITLE %}{{ current_page.title|e }}{% endblock -%}

{%- block PAGE_CONTENT -%}
<body data-lang="{{ request.LANGUAGE_CODE }}" class="{%- block BODY_CLASSES %}{% endblock %}">
    {%- if services -%}
        <section class="wide-tb-100 pos-rel">
            <div class="container">
                <div class="contact-map-bg option">
                    <ul>
                        {%- for service in services -%}
                        <li class="service-title">{{ service.title }}</li>
                        {%- endfor -%}
                    </ul>
                <div class="service-result">

                </div>
                </div>
            </div>
        </section>
    {%- endif -%}
</body>
{% endblock -%}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2019-11-07
@sergey-gornostaev

In the documentation, everything is simply and clearly described .

V
Vladimir, 2019-11-07
@Realmixer

Use the method GET. If it is the method that is needed POST, then add a value csrfmiddlewaretokenequal to the cookie csrftoken. In your case, in the function ajaxTestadd:
Here, the ancient jquery.cookie plugin is used as an example . Better find something newer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question