'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'


Solution 1:[1]

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))

Solution 2:[2]

Replace your code with following:

from django.http import JsonResponse

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

Instead of serializing and sending it via httpresponse.

Solution 3:[3]

This works for python 3.6 and Django 2.0

from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse
import requests

@login_required()
def get_some_items(request):
    headers = {"Authorization": "Token uydsajbkdn3kh2gj32k432hjgv4h32bhmf"}
    host = "https://site/api/items"

    response = requests.get(host, headers=headers)
    result = JsonResponse(response.json())

    return HttpResponse(result, content_type='application/json')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ikkuh
Solution 2 Abijith Mg
Solution 3 Сергей Зеленчук