将queryset数据作为变量模板传递给javascript

时间:2020-06-23 11:57:26

标签: javascript python python-3.x django django-models

我正在尝试将queryset数据作为javascript变量传递给模板。我知道我在做一些愚蠢的不起作用的事情。

views.py 

from django.http import HttpResponse
from django.template import Context,Template,RequestContext
from django.shortcuts import render_to_response, render
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.template.context_processors import csrf
from io import TextIOWrapper
from django.core.mail import send_mail
from django.utils.safestring import mark_safe
from django.db import connection
import os
import json
import xlrd
from django import forms
from django.forms import ModelForm
from django.db import models
from .models import Deliveries
# Create your views here.

def historicals(request):
    context = {}          
    historicals= Deliveries.objects.all()[1:100]
    print (historicals)
    context['historicals']=historicals
    context['abc']=123
    return render(request,'customer.html',context)

然后

customer.html
{% extends "base.html" %}
{% load static %}
    <script type="text/javascript">
    //{% autoescape off %}{{ historicals }}{% endautoescape %}; <--tried this too
           var actuals = {{ historicals | safe }};
           var abc = {{ abc | safe }}   ;
        </script>
        <script src="{% static 'js/custom.js' %}"></script>
    {% block content %}         
            {% for i in actuals %}
                {{ i.Date }}
            {% endfor %}            
            <h1> {{ abc }} </h1> 
    {% endblock content %}

在这里感到困惑。

  1. 当我打印历史记录时,查询集将显示在控制台中。它告诉我模型,到db和查询的连接正常。
  2. 我能够将值'abc'= 123传递给模板,并且它可以正确显示在customer.html中

历史查询集甚至没有显示在模板中(我检查了视图源,其空白)却显示了简单变量,这是我做错了什么?

1 个答案:

答案 0 :(得分:2)

您可以使用Django内置的serilizers将数据传递给js进行查询。

# views.py
from django.core import serializers

historicals = serializers.serialize("json", Deliveries.objects.all())

# html
<script type="text/javascript">
   // construct js objects
   var actuals = JSON.parse('{{ historicals | safe }}')
</script>

编辑

如果您想在Django模板中循环,则只需传递delivers查询集,而无需将其解析为js变量。

# views.py
diliveries = Deliveries.objects.all()

# html
{% for i in deliveries %}
  {{ i.Date }}
{% endfor %}