1
votes

Sorry for my English. I have some data from another server, but I need 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 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 did like 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'
3

3 Answers

3
votes

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

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.

0
votes

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