Django Ajax 'GET' return only strings

I am trying to get some data from my database using ajax, and iterate it.
for some reason, I get a long string, and not object that I can iterate.

views.py

def postHog(request):
if request.method == 'GET':
    pk = request.GET['megama']
    megama = Speciality.objects.get(id=pk)
    hog = Submain.objects.filter(speciality=megama)
    hogback = []
    for i in hog:
        if (i.image):
            hogback.append({"name": i.name, "desc": 
            i.desc, "image": i.image.url})
        else:
            hogback.append({"name": i.name, "desc": i.desc, "image": "None"})
response_data=json.dumps(hogback,ensure_ascii=False)
return JsonResponse({'hogback': response_data}, status=200,content_type="application/json")

urls.py

path(r'megamas/', views.postHog, name="post_hog"),

myjs.js

 $(".btnsmain").click(function () {
    $.ajax({
        type: 'GET',
        url: "/megamas",
        data:{
            megama:$("#id_main").val()
        },
        success:function (data) {

            $.each(data.hogback, function (index,element) {
                alert(index,element.name);

            });

        },
        error: function (data) {
            alert("not good");

        }
    })
});

if i use alert(hogback[0]) i get the “[”
its like i am getting back strings and not the list and dict objects.

thank you!

Solve it :slight_smile:

json.dumps() returns a json-formatted string.

JsonResponse takes data as a python object, so i don’t need to manually convert my data into json.

return JsonResponse({'hogback': hogback}, status=200,content_type="application/json")

Yes! Thank you for posting the solution after you fixed it.

Another couple improvements for your code:

  • You can use the require_GET decorator to lock your view to only GET requests. Currently it will crash for non-GET requests.
  • You should error if the required megama parameter is not there. Currently you’d crash with KeyError.
  • You should 404 if the Speciality doesn’t exist. You can use get_object_or_404 for this

Putting this together

@require_GET
def postHog(request):
    if "megama" not in request.GET:
        return JsonResponse("'megama' query parameter required", status=400)
    megama = get_object_or_404(Speciailiity, pk=request.GET['megama']
    ...

Additionally there’s no need to use an r-string for your your path.

Hope those help!

1 Like

you right, thank you. you make me a better devloper :slight_smile: i will use this best practice on my code now.