Пытаюсь настроить динамическую фильтрацию используя Ajax, но она не работает.
Моя сортировать список сотрудников без обновления страницы
views.py
@api_view(['GET'])
def sort(request):
sort_form = FormWorker(request.POST)
if sort_form.is_valid():
needed_sort = sort_form.cleaned_data.get("sort_form")
else:
needed_sort = 'ПИ'
workers = Worker.objects.all()
queryset = workers.order_by(sort_mapping.get(needed_sort))
serializer = WorkerSerializer(queryset, many=True)
return Response(serializer.data, status=HTTP_200_OK)
serializers.py
from .models import *
from rest_framework import serializers
class WorkerSerializer(serializers.ModelSerializer):
class Meta:
fields = '__all__'
model = Worker
urls.py
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views
app_name = 'workers'
urlpatterns = [
path('', views.index, name='worker_index'),
path('search_worker/', views.search_worker.as_view(),
name='search_worker'),
path('search/', views.Search.as_view(), name='search'),
path('sort/', views.sort, name='sort')
]
А это моя html страница. в самом низу я пытаюсь использовать Ajax.
{% extends 'base.html' %}
{% load static %}
<!-- Search form -->
{% block content %}
<form action="{% url 'workers:search' %}" method="get">
<input type="search" name="q" type="text"
placeholder="По имени">
<button type="submit" class="btn btn-primary">Поиск</button>
</form>
<form action="{% url 'workers:search' %}" method="get">
<input type="search" name="p" type="text"
placeholder="По ЗП">
<button type="submit" class="btn btn-primary">Поиск</button>
</form>
<form action="{% url 'workers:search' %}" method="get">
<input type="search" name="l" type="text"
placeholder="По Должности">
<button type="submit" class="btn btn-primary">Поиск</button>
</form>
<br>
<br>
<br>
<br>
<br>
<br>
<form action="{% url 'workers:sort' %}" method="get" id="my_sort"
class="sort-form">{% csrf_token %}
{{ sort_form }}
<p><input type="submit" name="sort" value="Сортировать" id="sort_button"></p>
</form>
{% for i in page_obj %}
<div class="wrapper" id="text_result">
<ul><li>ФИО:{{ i.full_name }}<br>
Должность:{{ i.position }}<br>
Заработная плата:{{ i.payment }}<br>
Дата трудоустройства:{{ i.start_work }}<br>
id:{{ i.pk }}
</li></ul>
{% endfor %}
</div>
{% include 'includes/paginator.html' %}
{% endblock %}
.wrapper {
background-color:#000;
color:#fff;
font-size:30px;
text-align:center;
line-height:160%;
}
{% block javascript %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#sort_button').submit(function () {
var serializedData = $('my_sort').serialize();
$.ajax({
data: serializedData,
console.log(data)
url: $('#my_sort').data('url'),
success: function (data)
{
$('#text_result').html(data)
}
})
});
});
</script>
{% endblock javascript %}