我正在尝试将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 %}
在这里感到困惑。
历史查询集甚至没有显示在模板中(我检查了视图源,其空白)却显示了简单变量,这是我做错了什么?
答案 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 %}