2

I'm attempting to return a JSON response from a query. I've seen examples such as (https://rayed.com/wordpress/?p=1508), but they don't incorporate passing the HTML template. I'm receiving an error "ictionary update sequence element #0 has length 510; 2 is required"

Model

class APCPlats(models.Model):
PlatsProjected = models.IntegerField(db_column='Projected', blank=True, null=True)
PlatsCompleted = models.IntegerField(db_column='Complete', blank=True, null=True)
Month = models.CharField(db_column='Month', max_length=200 , blank=True, null=True)

def __str__(self):
    return self.Month

class Meta:
    managed = True
    db_table = 'APCPlats'

View

def APCChart(request):
   apcdata = APCPlats.objects.all()
   apcchart = serializers.serialize('json', apcdata)

   return render(request, 'apc.html', JsonResponse(apcchart, safe=False))

Solution:

Create the following class:

class DecimalJSONEncoder(json.JSONEncoder):
def default(self, o):
    if type(o) == Decimal:
        # Here You can decide if You want decimal to be converted
        # to string or float.
        return float(o)
    if isinstance(o, datetime.datetime):
        #return o.replace(tzinfo=None).isoformat()
        return datetime.datetime.strftime(o, "%Y/%m/%d")
    return super(DecimalJSONEncoder, self).default(o)

How to use the class on your queryset:

json_data = json.dumps(queryset, cls=DecimalJSONEncoder)

Make sure you import the following:

from django.core.serializers.json import DjangoJSONEncoder
Matt
  • 33
  • 2
  • 7
  • 1
    Why are you trying to use HTML template with JSON? Are you trying to return HTML as JSON? JSON in HTML? What's the expected result? – kichik May 11 '17 at 00:04
  • Possible duplicate of [Django view returning json without using template](https://stackoverflow.com/questions/9262278/django-view-returning-json-without-using-template) – Håken Lid Nov 14 '17 at 14:44
  • @kichik I solved this issue a while back. I needed to convert queries in Django to JSON to pass into google chart API. All is good now. – Matt Nov 15 '17 at 15:18

1 Answers1

1

I understand you are trying to return a queryset to frontend with ajax. If this is the case, you dont need to render, all you need is Jsonresponse like:

return JsonResponse(appchart, safe=False)
Mani Shirvani
  • 188
  • 1
  • 8
  • To expound on the solution... jason_data = json.dumps(list(queryset), cls=DecimalJSONEncoder) – Matt Feb 14 '19 at 14:08