Currently, I am faced with the challenge of fetching a Django queryset and storing it in a JavaScript variable using Ajax.
I have attempted to employ the following code snippet for this purpose; however, I keep encountering the issue of "Queryset is not JSON Serializable." As I am relatively new to both Django and JSON formats, I am struggling to find a workaround. Any suggestions on how to resolve this would be greatly appreciated.
The relevant sections in my project are as follows:
$.ajax({
url: "http://127.0.0.1:8000/getPorts",
success: function(result){
var res = JSON.parse(result);
}
});
In 'views.py':
def getPorts(request):
JSONer = {}
ports = Port.objects.all()
JSONer['ports'] = ports
return HttpResponse(json.dumps(JSONer))
If anyone has alternative approaches or better practices for utilizing Ajax to communicate with views, please feel free to share your advice. Thank you!