AJAX query cascading dropdown in django

16 Views Asked by At

in the index.html, i have the ajax query in the following manner

if (selectedGrade) {
    $.ajax({
        type: "GET",
        url: "/get_fabri_options",
        headers: { "X-CSRFToken": csrftoken }, // Include CSRF token in the headers
        data: {
            'MARKE': selectedGrade
        },
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function(data) {
            debugger;
            $('#fabri_select').html(data);
        },
        error: function(xhr, textStatus, error){
            debugger;
            console.log(error)
        }
    });

In the views.py I have the function in the following mannner

def get_fabri_options(request):
    if request.method == 'GET':
        selected_grade = request.GET.get('MARKE')[0].split(",")
        if selected_grade:
            try:
                # Filter Fabri objects based on the correct field
                fabri_options = Fabri.objects.filter(NAME__icontains=selected_grade).values_list('NAME', flat=True)
                # ^ Using 'icontains' for case-insensitive matching
                # Return JSON response with options
                logger.info('xxxxxxx')
                logger.info(f'{fabri_options}')
                return JsonResponse(list(fabri_options), safe=False)
            except Exception as e:
                traceback.print_exc()
                return JsonResponse({'error': 'An error occurred'}, status=500)
        else:
            return JsonResponse({'error': 'No grade provided'}, status=400)
    else:
        return JsonResponse({'error': 'Invalid request'}, status=400)

In the models.py , I have the code in the following manner

class Fabri(models.Model):
    objects = None
    NAME = models.CharField(max_length=100)

    def __str__(self):
        return self.NAME

But still I am getting the empty query when i select the option in the dropdwon.

enter image description here

Can anyone help me with the problem here?

0

There are 0 best solutions below