[Fixed]-Django ajax form how to display the result after submission

1πŸ‘

βœ…

In your views.py -> ResultView you are overriding the get_queryset() function which should return a queryset.

so change your get_queryset like:

def get_queryset(self):
    return Result.objects.all()

and handle your post separately like:

from django.core import serializers

def post(self, request, *args, **kwargs):
    form = InputForm(request.POST)
    if form.is_valid():
        if self.request.is_ajax():
            company = form.cleaned_data['company']
            region = form.cleaned_data['region']
            queryset=Result.objects.filter(region=region).aggregate(Sum('sales'))
            return HttpResponse(json.dumps(queryset))
    else:
         return HttpResponse(form.errors)

Your ajax call:

$.ajax({
    data: $(this).serialize(), // get the form data
    type: $(this).attr('post'),
    dataType: 'json',
    url: "dupont_list/",
    success: function(data) {
        var html = "<table>"
        html += "<td>"+data['sales__sum']+"</td>"
        html += "</table>"
        $("#result").html(html);
    }
});

Leave a comment