django 'str' object has no attribute '_meta'

16,512

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))
Share:
16,512
r1299597
Author by

r1299597

Updated on June 28, 2022

Comments

  • r1299597
    r1299597 almost 2 years

    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'
    
  • r1299597
    r1299597 over 6 years
    thanks for your comment, i did like you say but have error Object of type 'ModelYears' is not JSON serializable i update question
  • r1299597
    r1299597 over 6 years
    thanks for your answer. I did like you say, but i have error the JSON object must be str, bytes or bytearray, not 'ModelYears' i updated question
  • ikkuh
    ikkuh over 6 years
    It seems I was wrong by assuming the type was a string. How did you create the response variable?
  • r1299597
    r1299597 over 6 years
    i use zeep library for xml request. My response i create like this response = client.service.getModelYears(accountInfo=account_info)
  • ikkuh
    ikkuh over 6 years
    I see, sadly I don't have experience with that library so I don't know what the type of your response variable. Maybe you can find that somewhere in documentation and see if there is a way to go from that to JSON.