Django: request.is_ajax() возвращает False

Я пытаюсь сделать поиск 'patient' Dynamic с помощью ajax. Все в моем коде работает хорошо, но я не знаю, почему request.is_ajax() всегда возвращает false. Я искал об этом, но пока не нашел решения, сейчас мой код выполняет поиск, но с изменением url и это означает, что js не работает. Я не знаю, как хорошо работать с javascript в Django, поэтому, пожалуйста, помогите мне. Вот мой views.py:

def index(request):

    ctx = {}
    url_parameter = request.GET.get("q")
    
    if url_parameter:
        queryset = Patient.objects.annotate(fullname=Concat('first_name', Value(' '), 'last_name'))
        patients = queryset.filter(fullname__icontains=url_parameter)
        #patients = Patient.objects.filter(name__icontains=url_parameter)
    else:
        patients = Patient.objects.all()

    ctx["patients"] = patients
    print(request.is_ajax())
    if request.is_ajax():
        html = render_to_string(template_name="patient/patients-results-partial.html",context={"patients": patients})
        data_dict = {"html_from_view": html}

        return JsonResponse(data=data_dict, safe=False)
    return render(request, "patient/index.html", context=ctx)

index.html:

{% extends 'base.html' %}
{% block content %}
  <div class="col-md-6 offset-md-4">


    {# part added for dynamic search#}
    {# icon and search-box #}
    <form class="form-inline">
      <i id="search-icon" class="fas fa-search" aria-hidden="true"></i>
      <input id="patient-input" class="form-control form-control-sm ml-3 w-75" type="text" placeholder="Search" aria-label="Search" name="q">
    </form>

    {# artist-list section #}
    <div id="replaceable-content" class="col-6">
      {% include 'patient/patients-results-partial.html' %}
    </div>


    
  </div>

    

  <div class="col-md-6 offset-md-4">
    <a href="{% url 'register_patient' %}" class="btn btn-primary">Ajouter un nouveau patient</a>
  </div>
  <div class="col-md-6 offset-md-4">

    <div class="table-responsive">
      <table class="table table-striped table-sm">
        <thead>
          <tr>
            <th>Prénom</th>
            <th>Nom</th>
            <th>Téléphone</th>
            <th>Sexe</th>
            <th>Date de naissance</th>
            <th>Docteur</th>
          </tr>
        </thead>
        <tbody>
          {% for field in patients %}
            <tr>
              <td>{{field.first_name}}</td>
              <td>{{field.last_name}}</td>
              <td>{{field.phone}}</td>
              <td>{{field.sex}}</td>
              <td>{{field.birth_date}}</td>
              <td>{{field.doctor}}</td>
              <td><a href="{{field.id}}/" class="btn btn-warning">Details</a></td>
            </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>

  </div>
{% endblock content %}

и вот мой js код:

const patient_input = $("#patient-input");
const search_icon = $('#search-icon');
const patients_div = $('#replaceable-content');
const endpoint = '/patient/';
const delay_by_in_ms = 700;
let scheduled_function = false;

let ajax_call = function (endpoint, request_parameters) {
    $.getJSON(endpoint, request_parameters)
        .done(response => {
            // fade out the patients_div, then:
            patients_div.fadeTo('slow', 0).promise().then(() => {
                // replace the HTML contents
                patients_div.html(response['html_from_view'])
                // fade-in the div with new contents
                patients_div.fadeTo('slow', 1)
                // stop animating search icon
                search_icon.removeClass('blink')
            })
        })
}


patient_input.on('keyup', function () {

    const request_parameters = {
        q: $(this).val() // value of patient_input: the HTML element with ID patient-input
    }

    // start animating the search icon with the CSS class
    search_icon.addClass('blink')

    // if scheduled_function is NOT false, cancel the execution of the function
    if (scheduled_function) {
        clearTimeout(scheduled_function)
    }

    // setTimeout returns the ID of the function to be executed
    scheduled_function = setTimeout(ajax_call, delay_by_in_ms, endpoint, request_parameters)
})

Я думаю, что этот вид вызова AJAX, чище и проще, чем то, что у вас в коде. Эта модель AJAX работает для меня. Возможно, этот js код поможет вам исправить вашу ошибку.

$('#form').on('submit', function (event) {
    event.preventDefault();
    const form = $(this);
    const submit_btn = form.find('#submit-button');

    $.ajax({
        url: 'your URL for send ajax call',
        type: 'POST', // Method of call, such as POST or GET
        data: 'data as JSON', // You can use 'form.serialize()' to
        beforeSend: function () {
            // This line calls before that AJAX is called.
        },
        success: function (data) {
            // If the back-end returns a JSON response with 200 status code, js will run this line.
        },
        error: function (data) {
            // If the back-end returns a JSON response with 400 status code, js will run this line.
        },
        complete: function () {
            // After success or error is called , this function will be called
        },
    })
})
Вернуться на верх