Passing objects from Django to Javascript DOM

前端 未结 14 1153
野的像风
野的像风 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:04

    Django querysets are serializable by JSON. Some field types (such as date, apparently), can't be serialized at is. A workaround for date objects is posted in another question on JSON and Python.

    I would recommend creating dictionaries directly in the JavaScript itself. Given models like this:

    class Article(models.Model):
        title = models.CharField(max_length=100)
        slug = models.SlugField()
        content = models.TextField()
    
    class Author(models.Model):
        article = models.ForeignKey("Article", related_name="authors")
        first_name=models.CharField(max_length=100)
        last_name=models.CharField(max_length=100)
    

    I'd do something like this in the template:

    
    

    If you maybe worded the question a little poorly and aren't planning on inserting code in a

提交回复
热议问题