Passing objects from Django to Javascript DOM

前端 未结 14 1152
野的像风
野的像风 2020-12-04 21:26

I\'m trying to pass a Query Set from Django to a template with javascript.

I\'ve tried different approaches to solve this:

1. Normal Approach - Javas

14条回答
  •  感动是毒
    2020-12-04 22:07

    You have to mark the string as safe to be sure it's not escaped.

    in one of my project I use it like this:

    # app/templatetag/jsonify.py
    from django import template
    from django.utils.safestring import mark_safe
    import json
    
    register = template.Library()
    
    @register.filter
    def jsonify(list):
        return mark_safe(json.dumps(list))
    

    and in the template

    {% load jsonify %}
    
    

    but you may prefer to just add mark_safe or use |safe in the template to avoid all > stuff

    If the problem is for handling complex python object you may have to do your handler like this: JSON datetime between Python and JavaScript

提交回复
热议问题