user8925307
user8925307

Reputation:

Sending JSON data from view in Django

I have to store some data in the window object to use it un the frontend rendering. I have a model:

from django.db import models
from tools.various.db import Base
from tools.files.fields import CustomImgField, IMAGES_DIRECTORY_ORIGINAL
from django.conf import settings

class myModel(Base):
    myName                     = models.CharField(max_length=100, verbose_name='myName')
    mySurname                  = models.CharField(max_length=100, verbose_name='mySurname')

I have a view:

from django.http import Http404
from django.views.generic import TemplateView
from django.http import JsonResponse
from json import dumps
from front.models import Language
from front.models import myModel


class BaseView(TemplateView):
    def get_context_data(self, **kwargs):
        context = super(BaseView, self).get_context_data(**kwargs)

        context['myData'] = myModel.objects.value()
        return context

And I want to retrieve myData as a JSON object and store it in window object:

  window.app = {
    data: {},
    settings: {
      staticUrl: '{{ STATIC_URL }}',
      urls: {},
      storedData: {{ myData|jsonify|safe }}
    }
  };

But I get this response:

[{'myName': u'foo', 'mySurname': u'bar', u'id': 1L, 'order': 0L}] is not JSON serializable

Does anyone knows what I'm doing wrong?

Thanks!

EDIT:

I just tried return list(context) as André Laszlo proposes: it returns

Exception Value: list indices must be integers, not str

But if I use:

    context['myData'] = list(myModel.objects.values())
    return context

It seems to work. I'm going to read the documentation about 'list()'.

Upvotes: 1

Views: 3208

Answers (2)

André Laszlo
André Laszlo

Reputation: 15537

I think that the problem is that your list is actually not a list, it's a QuerySet that just looks like a list when printed.

Have you tried:

context['myData'] = list(myModel.objects.values())
return context

I think it should return a list with dictionaries, which should be JSON serializeable. Please update your question with your results if it doesn't work.

Upvotes: 2

alexisdevarennes
alexisdevarennes

Reputation: 5632

You are returning a python dictionary, you need to serialize it to JSON using json.dumps()

You are already importing json but not making use of it.

from django.http import Http404
from django.views.generic import TemplateView
from django.http import JsonResponse
from json import dumps
from front.models import Language
from front.models import myModel

class BaseView(TemplateView):
    def get_context_data(self, **kwargs):
        context = super(BaseView, self).get_context_data(**kwargs)
        context['myData'] = myModel.objects.value()
        return dumps(context)

Additionally, you might want to read up on ujson - Faster than the builtin json library.

Preferably, if you are using Django 1.7+ you can do:

from django.http import Http404
from django.views.generic import TemplateView
from django.http import JsonResponse
from json import dumps
from front.models import Language
from front.models import myModel
from django.http import JsonResponse


class BaseView(TemplateView):
    def get_context_data(self, **kwargs):
        context = super(BaseView, self).get_context_data(**kwargs)

        context['myData'] = myModel.objects.value()
        return JsonResponse(context)

Upvotes: 2

Related Questions