E
E
Elvinchik2022-02-02 22:37:35
AJAX
Elvinchik, 2022-02-02 22:37:35

How to pass data from Django model to AJAX?

Django code:

class IndexView(View):
    def get(self, request):
        model = TireModel.objects.all()
        text = request.GET.get("button_text")
        if request.is_ajax():
            t = time()
            return JsonResponse({"seconds": t}, status=200)

        context = {
            "tires": model
        }
        return render(request, "index.html", context)

    def post(self, request):
        fields = ["en_mm", "height", "diametr", "season", "cartype"]
        qs = TireModel.objects.all().values_list()
        # qs1 = serialize_tires(qs)
        # print(qs1)

        for field in fields:
            if request.POST.get(field) != "" and request.POST.get(field) != "All":
                qs = qs.filter(**{field: request.POST.get(field)})
        
        return JsonResponse({"data": qs})


Code in AJAX:

$(document).on("submit", function(e) {
    e.preventDefault();

    $.ajax({
        type: 'post',
        url: '',
        data: {
            csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
        },
        success: function(response) {
            console.log(response)
        }
    })
})


How to send data from Django model to AJAX? But after the for loop, the qs variable outputs an empty QuerySet()
for field in fields:
            if request.POST.get(field) != "" and request.POST.get(field) != "All":
                  qs = qs.filter(**{field: request.POST.get(field)})
                  print(qs)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
soremix, 2022-02-02
@soremix

So you did not send a single field to Ajax. In the request, only the ksrf token is there and that's it. Other fields must also be added.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question