Django Template - Convert a Python list into a JavaScript object

django template split string
django custom template tags
django template queryset
django template comment
invalid filter: 'jsonify'
django template in list
display json data in django template
django template join list

I am working on a Django / Python website. I have a page where I want to display a table of search results. The list of results is passed in to the template as normal.

I also want to make this list of objects accessible to the JavaScript code.

My first solution was just create another view that returned JSON format. But each page load required calling the query twice. So then I tried only downloading the data using the JSON view and printing the table using JavaScript.

But this is also not desirable as now the presentation layer is mixed into the JavaScript code.

Is there a way to create a JavaScript object from the Python list as the page is rendered?

How about a filter that dumps a Python value to JSON? Here's a sample implementation:

Since a JSON value also happens to be a valid right-hand side for a Javascript assignment, you can simply put something like...

var results = {{results|jsonify}};

inside your script.

It's nice to be able to quickly make Python lists and dictionaries into JSON. Change History (51) That is, binding some data to a JavaScript variable. The library parses JSON into a Python dictionary or list. It can also convert Python dictionaries or lists into JSON strings. We often came across a situation where we need to convert from one data structure to another. Python has so many data structures to work with, and each structure adds something to the table.


I created a custom template filter, see custom template tags and filters.

from django.core.serializers import serialize
from django.db.models.query import QuerySet
from django.utils import simplejson
from django.utils.safestring import mark_safe
from django.template import Library

register = Library()

def jsonify(object):
    if isinstance(object, QuerySet):
        return mark_safe(serialize('json', object))
    return mark_safe(simplejson.dumps(object))

register.filter('jsonify', jsonify)
jsonify.is_safe = True   

The calls to mark_safe are important. Otherwise Django will escape it.

In the template:

//Without template filter (you'll need to serialise in the view)
var data = jQuery.parseJSON('{{ json_data|safe }}');

//Using the template filter    
var data2 = jQuery.parseJSON('{{ record_list|jsonify }}');

Note the single quotes around the template tag.

Although my next question would be - is it REALLY safe?


An updated version working in django 1.8 of the above template tag that also handles being passed a flat values list, ie. values_list('myfield', flat=True):

from django.core.serializers import serialize
from django.db.models.query import QuerySet, ValuesListQuerySet
from django.template import Library

import json

register = Library()

@register.filter( is_safe=True )
def jsonify(object):

    if isinstance(object, ValuesListQuerySet):
        return json.dumps(list(object))
    if isinstance(object, QuerySet):
        return serialize('json', object)
    return json.dumps(object)

If the variable evaluates to a Template object, Django will use that object as the parent You can loop over a list in reverse by using {% for obj in list reversed %} . This operator is supported by many Python containers to test whether the given This does not make the string safe for use in HTML or JavaScript template  Convert list with each element an object of class into json Tag: python , json , flask I have a python list where each element in the list is the object of a class Summershum.Model.File:

New in Django 2.1: json_script

Django 2.1 introduced a new template tag: json_script. It is almost exactly what you are looking for, it might be even better. It converts a Python value into JSON, wrapped in a <script> tag. So this template:

{{ value|json_script:"foobar" }}

... would produce this:

<script id="foobar" type="application/json">{"example": "example"}</script>

This is not a normal Javascript <script> tag, it doesn't run, it's just JSON. If you want to access the contents in your Javascript, you can do so like this:

var value = JSON.parse(document.getElementById('foobar').textContent);

This tag has been coded so that it is properly escaped, a string with </script> in it won't break anything, for instance.

The for tag in Django will loop over each item in a list, making that item The slugify filter will convert the spaces of a string into hyphens and convert the string to Django loads the page and returns in a JavaScript object that you can then Unlike select_related , prefetch_related does its magic in Python,  For a JavaScript object stored in a Django field as text, which needs to again become a JavaScript object dynamically inserted into on-page script, you need to use both escapejs and JSON.parse(): var CropOpts = JSON.parse("{{ profile.last_crop_coords|escapejs }}");

Look this answer too.

But it isn't highload way. You must:

a) Create JSON files, place to disk or S3. In case is JSON static

b) If JSON is dynamic. Generate JSON on separately url (like API) in your app.

And, load by JS directly in any case. For example:


P.S.: Sorry for my English.

Django's templates are not simply Python code embedded into HTML. Style Sheets (CSS), semantic markup and JavaScript in the front end to create the This is a sample of the template tags, variable methods and filters available in Django. Note that Django will search your DIRS list in the order listed, so keep in mind  Django knows how to convert these Python values into their corresponding database type. The output_field argument should be a model field instance, like IntegerField() or BooleanField(), into which Django will load the value after it’s retrieved from the database.

The list is available in template (template.html) by using. {% for shbf in That will convert a Django queryset into a JSON object. Then, in your JS But note that not all python objects can be sent this way. You can't, for  If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template. See Template inheritance for more information. Normally the template name is relative to the template loader’s root directory.

Let's focus on the parts which are relevant to adding Vue.js into a Django project. added to a list, and the list is passed on inside a context dictionary to the template. As the template is going to change quite a bit, I created a new one, and called it This way, we get a JavaScript variable people which is being set to the  The Django template language¶ This document explains the language syntax of the Django template system. If you’re looking for a more technical perspective on how it works and how to extend it, see The Django template language: for Python programmers. Django’s template language is designed to strike a balance between power and ease.

You should be able to serialize the data as JSON, and pass it down in an object in a script tag. This way, you can access the injected code as a global. 10.1K views  For the time series we need to convert Python’s datetime objects to Javascript Date objects and we do so in line 44. line 62-69 vectorises the tweet content to tf-idf counts, which is a common