Django Template - Convert a Python list into a JavaScript object

后端 未结 4 1501
谎友^
谎友^ 2020-12-30 02:19

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.

4条回答
  •  暖寄归人
    2020-12-30 02:59

    Solution

    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 }}');
    alert(data.length);
    
    //Using the template filter    
    var data2 = jQuery.parseJSON('{{ record_list|jsonify }}');
    alert(data2.length);
    

    Note the single quotes around the template tag.

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

    Update

    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)
    

提交回复
热议问题