user2162611
user2162611

Reputation: 175

pass queryset data to javascript as a variable template

I am trying to pass queryset data to the template as a javascript variable. I know I am doing something silly that is not working.

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)

then the

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 %}

Heres the confusion.

  1. When I print the historicals, the queryset shows in the console. It tells me that models, the connectivity to db and query is working.
  2. I am able to pass value 'abc' =123 to the template and it shows up in customer.html correctly

What am I doing wrong for the historicals queryset to not even show up in the template (I checked view source, its blank) but simple variable shows up?

Upvotes: 3

Views: 6313

Answers (1)

minglyu
minglyu

Reputation: 3337

You can use Django builtin serilizers to pass data to js for queryset.

# 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>

EDIT

if you would like to loop in django template, you just need to pass delivers queryset, no need parse as js variables.

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

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

Upvotes: 9

Related Questions