2

The error occurs in the controller function call. returns an array of data. I need to pass this array to the template.

views.py:

def new_authors(request):   
    new_authors = UserProfile.get_new_authors_entries()

    # UserProfile.get_new_authors_entries() retrun:
    #[
    #   {
    #       'id': 4, 
    #       'username': 'zzzzzz'
    #   }, 
    #   {
    #       'id': 5, 
    #       'username': 'wwwwww'
    #   }
    #]

    return HttpResponse(json.dumps(new_authors), content_type='application/json')   

But I get the following error message:

File "/usr/lib/python3.4/json/encoder.py", line 173, in default
    raise TypeError(repr(o) + " is not JSON serializable") TypeError: [{'id': 4,  'username': 'zzzzzz'}, {'id': 5, 'username': 'wwwwww'}] is not JSON serializable

models.py:

class UserProfile(User):            


    @classmethod
    def get_new_authors_entries(self, cut_begin=0, cut_end=2):
        return self.objects.filter(is_active=1, is_superuser=0).values('id', 'username')[cut_begin:cut_end] 
dert
  • 51
  • 5
  • I believe the issue is coming from trying to serialize your `datetime` object. If so, [this may help](http://stackoverflow.com/questions/11875770/how-to-overcome-datetime-datetime-not-json-serializable-in-python) – Cory Kramer Oct 10 '14 at 12:52
  • Also take a look at: https://docs.djangoproject.com/en/dev/topics/serialization/ – Brandon Taylor Oct 10 '14 at 12:53
  • 2
    You should show us exactly what `get_new_authors_entries` does. I suspect it returns a ValuesQuerySet, not a dictionary. – Daniel Roseman Oct 10 '14 at 12:53

1 Answers1

1

As this post suggests, you could use the default parameter of json.dumps to handle your problem:

>>> dthandler = lambda obj: (
...     obj.isoformat()
...     if isinstance(obj, datetime.datetime)
...     or isinstance(obj, datetime.date)
...     else None)
>>> json.dumps(datetime.datetime.now(), default=dthandler)
'"2010-04-20T20:08:21.634121"'

I had the same problem with serializing a datetime object and this helped.

Peace

Community
  • 1
  • 1
Oscar
  • 231
  • 4
  • 17