Skip to content
Advertisement

django ‘str’ object has no attribute ‘_meta’

Sorry for my English. I have some data from another server, but I need to output this data like JSON.

if i print response in console:

{
    'responseStatus': {
        'status': [],
    },
    'modelYear': [
        1981,
        1982
      
    ]
}

but, if i return this response like HttpResponse i have an error

AttributeError: ‘str’ object has no attribute ‘_meta’

this my code:

data = serializers.serialize('json', response, ensure_ascii=False)
return HttpResponse(data, content_type="application/json")

UPD:

I tried with this:

from django.http import JsonResponse

def some_view(request):
    ...
    return JsonResponse(response, safe=False)

but have error:

Object of type ‘ModelYears’ is not JSON serializable

UPD:

I did like this:

import json
from django.http import JsonResponse

def some_view(request):
        ...
        return JsonResponse(json.loads(response))

but have error:

the JSON object must be str, bytes or bytearray, not 'ModelYears'

Advertisement

Answer

The Django docs says the following about the serializers framework:

Django’s serialization framework provides a mechanism for “translating” Django models into other formats.

The error indicates that your variable response is a string and not an Django model object. The string seems to be valid JSON so you could use JsonResponse:

import json
from django.http import JsonResponse

# View
return JsonResponse(json.loads(response))
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement