Skip to content

Instantly share code, notes, and snippets.

@rjloura
Created January 18, 2017 01:37
Show Gist options
  • Save rjloura/6e1e582b76d9f724ef8a4dff5457d8c5 to your computer and use it in GitHub Desktop.
Save rjloura/6e1e582b76d9f724ef8a4dff5457d8c5 to your computer and use it in GitHub Desktop.
Convert queryset to JSON for use with javascript
Using the JSONEncoder from: https://github.com/bradjasper/django-jsonfield/blob/master/jsonfield/encoder.py
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
tl = Model.objects.filter(year=self.kwargs['year']).values()
ctx['jsonstring'] = json.dumps(tl, cls=JSONEncoder)
return ctx
Then in the template:
var json_data = {{ jsonstring|safe }};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment