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.

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":, "desc": 
            i.desc, "image": i.image.url})
            hogback.append({"name":, "desc": i.desc, "image": "None"})
return JsonResponse({'hogback': response_data}, status=200,content_type="application/json")

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


 $(".btnsmain").click(function () {
        type: 'GET',
        url: "/megamas",
        success:function (data) {

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


        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

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.