Answer the question
In order to leave comments, you need to log in
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})
$(document).on("submit", function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '',
data: {
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
},
success: function(response) {
console.log(response)
}
})
})
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question