I am using Django and AJAX to implement a chained-dropdown. The user will first be prompted to select a brand_name from a dropdown, and depending upon the brand_name selected, all the names of the products that are made by that brand will be displayed in the second dropdown.
views.py
def chained_dropdown(request):
if request.method == "POST":
brand = request.POST['brand']
print(brand)
sort_by_brand = list(models.Product.objects.filter(brand=brand).order_by('product_id').values('product_id', 'product_name'))
data = {
'SortByBrand': sort_by_brand
}
return JsonResponse(data)
AJAX request:
var brand = $('#brand').val()
$.ajax({
type: "POST",
url: "/changeddropdown",
data:{
"brand": brand,
}, success: function (data){
// What should I do here?
console.log(data)
},
})
templates snippet: This is where I want the product names to be displayed, and the option value should be their corresponding product_id.
<label for="product_id"> Product ID</label>
<select name="product_id" id="product_id">
<option disabled selected="true"> --Select -- </option>
<option value=""> </option>
</select>
For your reference, this is what console.log(data) prints:
{SortByBrand: [{product_id: 31, product_name: "Lotion"}, {product_id: 32, product_name: "Deo"}]}
I am having trouble displaying this information in the template, any help would be greatly appreciated.