using reverse url in javascript - javascript

I need to add event listener to standard django select field.
The listener will (in the future) do htmx.ajax call ( https://htmx.org/api/#ajax )
urls.py
from django.urls import path
from .views import mailtemplate_GetSchema, refresh_schema
from .views import surat_schema_table
urlpatterns = [
path('htmx/surat_schema_table/<str:template_id>', surat_schema_table, name='surat_schema_table'),
]
currently I have a test template.
This template will not do ajax call, just display final url tobe called
form template ( surat_form_htmx.html )
{% extends "admin/change_form.html" %}
{% block after_field_sets %}
<!--- add htmx -->
<script src="https://unpkg.com/htmx.org#1.6.0"></script>
<style>
/* DivTable.com */
.divTable{
display: table;
width: 100%;
}
.divTableRow {
display: table-row;
}
.divTableCell, .divTableHead {
border: 1px solid #999999;
display: table-cell;
padding: 3px 10px;
}
.divTableHeading {
display: table-header-group;
font-weight: bold;
}
.divTableFoot {
background-color: #EEE;
display: table-footer-group;
font-weight: bold;
}
.divTableBody {
display: table-row-group;
}
</style>
<!-- EOF evt listener id_template -->
Obj ID: <input id="loaded_object" id="loaded_object" type="text" size="20" readonly {% if not add %} value="{{ obj_id }}" {% endif %}>
Selected Template: <input id="selected_template" name="selected_template" type="text" size="20" readonly >
url: <input id="call_url" name="call_url" type="text" size="20" readonly >
<script>
const selectElement = document.querySelector("#id_template");
selectElement.addEventListener('change', (event) => {
var result = document.getElementById("id_template").value ;
var url_final={% url surat_schema_table result %} ;
document.getElementById('selected_template').value = result;
document.getElementById('call_url').value = url_final;
});
</script>
<!-- EOF evt listener id_template -->
<div id="container_for_surat_schema_table">
</div>
{% endblock %}
admin.py
from django.contrib import admin
from .models import Surat
class SuratAdmin(admin.ModelAdmin):
change_form_template = 'surat_form_htmx.html'
admin.site.register(Surat, SuratAdmin)
currently it produce a traceback when loaded:
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/myapp/surat/add/
Django Version: 4.1.5
Python Version: 3.10.6
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Template error:
In template /home/bino/Documents/dynform/htmx01/myapp/templates/surat_form_htmx.html, error at line 44
Reverse for '' not found. '' is not a valid view function or pattern name.
34 : <!-- EOF evt listener id_template -->
35 : Obj ID: <input id="loaded_object" id="loaded_object" type="text" size="20" readonly {% if not add %} value="{{ obj_id }}" {% endif %}>
36 : Selected Template: <input id="selected_template" name="selected_template" type="text" size="20" readonly >
37 : url: <input id="call_url" name="call_url" type="text" size="20" readonly >
38 :
39 : <script>
40 : const selectElement = document.querySelector("#id_template");
41 :
42 : selectElement.addEventListener('change', (event) => {
43 : var result = document.getElementById("id_template").value ;
44 : var url_final= {% url surat_schema_table result %} ;
45 : document.getElementById('selected_template').value = result;
46 : document.getElementById('call_url').value = url_final;
47 :
48 : });
49 :
50 : </script>
51 : <!-- EOF evt listener id_template -->
52 :
53 : <div id="container_for_surat_schema_table">
54 :
Traceback (most recent call last):
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
response = get_response(request)
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/core/handlers/base.py", line 220, in _get_response
response = response.render()
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/response.py", line 114, in render
self.content = self.rendered_content
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/response.py", line 92, in rendered_content
return template.render(context, self._request)
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/backends/django.py", line 62, in render
return self.template.render(context)
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/base.py", line 175, in render
return self._render(context)
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/base.py", line 167, in _render
return self.nodelist.render(context)
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/base.py", line 1005, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/base.py", line 1005, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/loader_tags.py", line 157, in render
return compiled_parent._render(context)
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/base.py", line 167, in _render
return self.nodelist.render(context)
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/base.py", line 1005, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/base.py", line 1005, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/loader_tags.py", line 157, in render
return compiled_parent._render(context)
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/base.py", line 167, in _render
return self.nodelist.render(context)
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/base.py", line 1005, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/base.py", line 1005, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/loader_tags.py", line 157, in render
return compiled_parent._render(context)
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/base.py", line 167, in _render
return self.nodelist.render(context)
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/base.py", line 1005, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/base.py", line 1005, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/loader_tags.py", line 63, in render
result = block.nodelist.render(context)
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/base.py", line 1005, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/base.py", line 1005, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/loader_tags.py", line 63, in render
result = block.nodelist.render(context)
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/base.py", line 1005, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/base.py", line 1005, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/template/defaulttags.py", line 472, in render
url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/urls/base.py", line 88, in reverse
return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
File "/home/bino/.venv/htmx01/lib/python3.10/site-packages/django/urls/resolvers.py", line 828, in _reverse_with_prefix
raise NoReverseMatch(msg)
Exception Type: NoReverseMatch at /admin/myapp/surat/add/
Exception Value: Reverse for '' not found. '' is not a valid view function or pattern name.
looks like that 'var result' is read as just " '' " by template.
My question is:
How to use/call reverse url in javascript with variable from 'var' inside django template.

var url_final={% url surat_schema_table result %}
should be something like var url_final={% url "surat_schema_table" template_id="..." %}
(must fit to the urlspattern definition)

Related

Error "TypeError: Cannot read property 'email' of undefined" using AngularJS and Ionic

I have the following form using AngularJS and Ionic:
<ion-modal-view class="game" ng-controller="PdfsmtpCtrl">
<ion-header-bar class="bar bar-balanced">
<a class="button button-icon icon ion-close-circled" ng-click="hideInformation()"></a>
<h1 class="title">PDF-Export per Email</h1>
<a type="submit" ng-click="getPdf(user)" class="button button-icon icon ion-checkmark-circled"></a>
</ion-header-bar>
<ion-content scroll="false" class="game">
<div>
<form novalidate class="simple-form">
<label>E-mail: <input type="email" ng-model="user.email" /></label><br />
<input type="submit" ng-click="getPdf(user)" value="Save" />
</form>
</div>
</ion-content>
</ion-modal-view>
UPDATE: Here is the related AngularJS code:
'use strict';
angular.module('app')
.controller('PdfsmtpCtrl', function ($scope, Pdfsmtp)
{
$scope.pdfsmtp = new Pdfsmtp();
$scope.hideInformation = function ()
{
$scope.pdfsmtpModal.hide();
};
//joey: PDF to generate
$scope.getPdf = function (user)
{
var user = angular.copy(user);
var emailReceiver = user.email;
var emailSubject = "<SubjectText>";
var emailBody = "<BodyText>";
var emailSender = "<EmailAddress>";
var fileName = "<FileName.pdf>";
var hostName = "<SenderHostName>";
var contentType = "application/pdf";
var doc = new jsPDF
({
orientation: 'p', // p = portrait, l = landscape
unit: 'mm',
format: [210, 297],
});
//joey: Simon Bengtsson and his autotable
doc.setFontSize(22);
doc.setTextColor(23, 154, 85);
doc.text(("<SomeText>"), 14, 15);
doc.autoTable(
{
startY: 30,
startX: 30,
headStyles: {fillColor: [25, 141, 79] },
footStyles: {fillColor: [25, 141, 79] },
theme: 'grid',
styles:
{
overflow: 'linebreak',
lineWidth: 0.5,
lineColor: [25, 141, 79]
},
html: '#resultTable',
});
var finalY = doc.lastAutoTable.finalY || 20;
doc.setTextColor(23, 154, 85);
doc.text('Table: Signature:', 14, finalY + 20);
var blob = doc.output();
var dataUri = "data:" + contentType + ";base64," + btoa(blob);
Email.send(
{
Host: hostName,
Username: emailSender,
Password: "<somepassword>",
To: emailReceiver,
Attachments :
[{
name : fileName,
data : dataUri
}],
From: emailSender,
Subject: emailSubject,
Body: emailBody
}).then($scope.hideInformation());
//}).then(message => alert(message)
}
});
When clicking Save in the form all goes well as the variable user will be taken over by the related function.
When clicking the icon for Submit in <ion-header-bar> the following error can be seen as the variable user is undefined:
TypeError: Cannot read property 'email' of undefined
What needs to be done that Submit can be used?
You should initialize the user object. That way the object won't be undefined when you are trying to access the email property.
$scope.pdfsmtp = new Pdfsmtp();
$scope.user = { email : ''};

Corrupted or Blank file is getting by email through Web app - Google script

Question
Below google script running fine but the file uploaded send via email is corrupted or blank while getting through email.. Attached filename, content type are same as uploaded... but getting file cannot be opened.. text files are fine... Could any one can help in this regard.
Code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile('index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function processForm(formObject) {
var myFile = formObject.myFile;
var FileBytes = myFile.getBytes();
var FileType = myFile.getContentType();
var FileName = myFile.getName();
var FileToSend = {
fileName: FileName,
content: FileBytes,
mimeType: FileType
};
// Logger.log(FileType);
var FileBytes2 = [100, 97, 121, 32, 108, 97, 32, 110, 111, 105, 32, 100, 117, 110, 103, 32, 98, 101, 110, 32, 116, 114, 111, 110, 103];
var FileToSend2 = {
fileName: 'test222.txt',
content: FileBytes2,
mimeType: 'text/plain'
};
var FileToSend3 = {
fileName: 'test333.txt',
content: 'noi dung ben trong',
mimeType: 'text/plain'
};
GmailApp.sendEmail('email#domain', '6 Attachment example', '6 Please see the attached file.', {
attachments: [FileToSend, FileToSend2, FileToSend3],
name: '6 Automatic Emailer Script'
});
return FileName;
}
index.html
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
function handleFormSubmit(formObject) {
google.script.run.withSuccessHandler(updateUrl).processForm(formObject);
}
function updateUrl(filename) {
var div = document.getElementById('output');
div.innerHTML = filename;
}
</script>
</head>
<body>
<form action="#" id="myForm" onsubmit="handleFormSubmit(this)" method="post" enctype="multipart/form-data">
<div class="file-field input-field">
<div class="btn">
<span>File</span>
<input name="myFile" type="file" multiple>
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text" placeholder="Upload one or more files">
</div>
</div>
<input type="submit" value="Submit" />
</form>
<div id="output"></div>
</body>
</html>
To solve your issue, in the handleFormSubmit function, I took an array buffer and transformed it into a string containing the file data and pass it to your processForm function, in order for that logic to be handled in the frontend instead of the backend, google.script.run is a little picky with the values you can pass as arguments. Therefore, your handleFormSubmit function will look like this now:
const handleFormSubmit = async (formObject) => {
// Get all the file data
let file = formObject.myFile.files[0];
// Get binary content, we have to wait because it returns a promise
let fileBuffer = await file.arrayBuffer();
// Get the file content as binary and then pass it to string
const data = (new Uint8Array(fileBuffer)).toString();
// Pass the file meta data and the content
google.script.run.withSuccessHandler(updateUrl).processForm(file.name, file.type, data);
}
As for the backend function processForm , you will need to transform the data string into a binary data array again, that's why I use JSON.parse("[" + data + "]"). Now, your processForm will look like this:
function processForm(name, type, data) {
var fileToSend = {
fileName: name,
// Convert the string to a Binary data array
content: JSON.parse("[" + data + "]"),
mimeType: type
};
GmailApp.sendEmail('email#domain', '6 Attachment example', '6 Please see the attached file.', {
attachments: [fileToSend],
name: '6 Automatic Emailer Script'
});
return "this file " + name + " has just been sent to your email";
}

Sending JSON Data from Python to Javascript and accessing them.

I have a python file that gets the data from database and returns them in the form of JSON.
import pymysql;
import json;
from flask import Flask, render_template, request, redirect, Response
app = Flask(__name__)
#app.route('/test', methods=["POST", "GET"])
def getMySQlData():
tableData = []
connection = pymysql.connect(host='db-auto-performancetesting',
user='DBUser',
password='*******',
database='DbPerformanceTesting',
port=3302,
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
sql = "SELECT TestcaseName, AverageExecutionTimeInSeconds FROM PASPerformanceData WHERE BuildVersion='38.1a141'"
cursor.execute(sql)
while True:
row = cursor.fetchone()
if row == None:
break
tableData.append(row)
tableDataInJson = json.dumps(tableData, indent=2)
print tableDataInJson
return tableDataInJson
finally:
connection.close()
if __name__ == "__main__":
app.run()
I need help in collecting this JSON data into HTML & Javascript and use them as the chart data.
I am new to Javascript and ajax. Can someone help me in writing ajax call to python file from Javascript and retrieve the JSON data returned.
<!DOCTYPE HTML>
<html style="height:100%;">
<head>
<style type="text/css">
body {
overflow:hidden;
}
</style>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var chart1 = new CanvasJS.Chart("chartContainer1", {
title:{
text: "Launch Application"
},
axisY:{
title: "Average Execution Time(seconds)"
},
axisX:{
title: "Software Version",
labelAngle: 180
},
data: [
{
// Change type to "doughnut", "line", "splineArea", etc.
indexLabelFontSize: 16,
labelFontSize: 16,
type: "column",
dataPoints: [
{ label: "ReleaseVersion \n (20.1a121)", y: "**Data recieved from JSON, indexLabel**": "6.0 s" },
{ label: "PreviousVersion \n (38.1a140)", y: "**Data recieved from JSON**", indexLabel: "5.0 s" },
{ label: "CurrentVersion \n (38.1a.141)", y: "**Data recieved from JSON**", indexLabel: "5.4 s" }
]
}
]
});
Thanks
So let me give you quick overview of how might AJAX and flask work together.
Lets say you have some data that you get from database which is something like this
items=[{"id":123,"name":"abc","lastname":"xyz"}]
And you could store something like this with a small piece of code which would be something like this
result = cursor.fetchall()
links = []
num = 0
for item in result:
if links.__len__()-1 != num:
links.append({})
links[num]['id'] = item[0]
links[num]['name'] = item[1]
links[num]['lastname'] = item[2]
#links.append({}) extra append should be created
num += 1
Now the interesting AJAX part
Lets say you have a simple form that you would want to submit.
<form id="searchForm" action="/" method="POST">
<input type="text" id="search" name="search" placeholder="Search">
<input type="submit" value="Search">
</form>
To stop default action for submit you can have a script which would be something like this
$(document).ready(function() {
//#addLinkForm is nothing but the id of the form (works well if you have multiple forms in your page)
$('#addLinkForm').on('submit',function(event){
//This is where the data is sent
$.ajax({
url: '/adminAJAX',
type: 'POST',
data: $('#addLink'),
})
//this is done when the response is received
.done(function(data) {
console.log("success " + data);
});
event.preventDefault();
});
});
The response would be in your browser console. The data received can be used as you see fit
For this to work you would also need
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
in your HTML code
One last thing. For all of this to work you would also need your server side which i guess would be flask for you
#app.route('/adminAJAX',methods=['POST'])
def adminAJAX():
#your processing logic
items=[{"id":123,"name":"abc","lastname":"xyz"}] #just an example
return json.dumps(items)

Hogen.js - Load nested template with JS

I got a postings template (Hogen.js) were I load data (api call from Laravel 5.3) into it.
I managed to load, compile and render the template and the data correctly.
Problem:
I have jquery/vanilla js scripts that need to work with the template and the data but somehow this JS is completely ignored by the rendered template and it doesn't work (onClick, other ajax calls etc.).
My load/render JS:
var $page = 1;
var source = $("#postTemplate").html();
var template = Hogan.compile(source);
$.ajax({
url: '/api/postings',
data: { page: $page} ,
type: 'POST',
success: function(data) {
var output = template.render(data);
$('.posts-container').prepend(output);
}
});
My Template:
<script id="postTemplate" type="text/x-hogan-template">
#{{#posts.data}}
<div class="post">
<div class="image">
<img src="#{{ imageURL }}" alt="post image" />
</div>
<div class="info">
<div class="like-count" data-like-id="#{{ id }}">
more html
</div>
</div>
#include('partials.comments')
</div>
#{{/posts.data}}
</script>
I include a partial from laravel with my "comment" code that needs to be execuded aswell (fadeIn, ajaxacalls,submit etc.)
Is it possible, that I cann ot execute my JS with the newly rendered template or DOM, because it's not available at document.ready?
Do I need to switch my template engine? Any other way to make this work?
JSON:
{
"success": true,
"posts": {
"total": 46,
"per_page": 20,
"current_page": 3,
"last_page": 3,
"next_page_url": null,
"prev_page_url": "http://localhost/api/postings?page=2",
"from": 41,
"to": 46,
"data": {
"40": {
"id": 6,
"name": " ",
"imageURL": "",
"city": "Spanien",
"country": "",
"created_at": "2018-03-11 09:40:25",
"profilePictureURL": null,
"social_src": 0,
"mediumImageURL": null
}
}
}
}
I stripped it down a bit!
You cannot use
#include('partials.comments')
in your hgan.js template. Hogan is (almost) logicless. It is for binding JSON to HTML templates, it is not capable or intended for this use.
Partials can only be used like folows:
var partialText = "normal text but can use {{foo}} is from a variable";
var p = Hogan.compile(partialText);
var text = "This template contains a partial ({{>partial}})."
var t = Hogan.compile(text);
var s = t.render({foo: chickens}, {partial: p});
is(s, "This template contains a partial (normal text but we can use chickens. is a variable).", "partials work");
Basically {{>partial}} can be used to nest another precompiled template.

Django template not executing js function

I have a django template that looks like this:
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script>
<script src="{{ STATIC_URL }}js/jquery.flot.js"></script>
<!--<script src="c:/src/project/scraper/collegedata/templates/chart.js" type="text/javascript"></script>-->
<script src="{{ STATIC_URL }}js/chart.js" type="text/javascript"></script>
</head>
<body>
<div id="chart1" style="width:600px;height:300px"></div>
<script>
show_graph("{{ chart_type }}", {{ series_names }}, {{ data }}, {{ answer }});
</script>
<form action="start">
<input type="submit" value="Back to Questions" />
</form>
</body>
</html>
where show_graph is a function in chart.js. However, pycharm gives me one of two errors, either:
unresolved function or method show_graph(), or
invalid number of parameters passed: expected 4
and the function is clearly not being called.
I'm a little confused as to whether or not I can even pass template vars to a js function at all...
Does anyone have any insight?
EDIT:
this generates
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script>
<script src="/static/js/jquery.flot.js"></script>
<!--<script src="c:/src/project/scraper/collegedata/templates/chart.js" type="text/javascript"></script>-->
<script src="/static/js/chart.js" type="text/javascript"></script>
</head>
<body>
<div id="chart1" style="width: 600px; height: 300px;"></div>
<script>
show_graph("pie", [<ResponseOption: puddentane>, <ResponseOption: down the lane>], [1, 0], 0);
</script>
<form action="start">
<input value="Back to Questions" type="submit">
</form>
</body></html>
where chart.js looks like (values temporarily hardcoded for troubleshooting, and it should be mentioned that $.plot also gives an unresolved function error):
function show_graph(charttype, series_names, data, answer_index){
var data = [2000, 50, 400, 200, 5000];
var data3 = [
{ label: "my cat", data: 10, color: 'rgb(85, 96, 42)'},
{ label: "my friends", data: 20, color: 'rgb(105, 118, 52)'},
{ label: "my boyfriend", data: 30, color: 'rgb(125, 141, 62)'},
{ label: "my job", data: 30, color: '#42215F'},
{ label: "food", data: 10, color: 'rgb(145, 164, 72)'},
{ label: "social skills", data: 0, color: 'rgb(166, 189, 82)'}
];
alert("in chart.js");
var charttype = "pie";
var type = {};
type[charttype] = {show: true};
var chart_options = {};
chart_options["series"]=type;
var plot = $.plot($("#chart1"), data3, chart_options);
}
It looks like series_names is just being output as the HTML entities of an object without a proper __unicode__ method. You're getting:
show_graph("pie", [<ResponseOption: puddentane>,
Which, decoded, is:
show_graph("pie", [<ResponseOption: puddentane>, ...
What actually needs passing to the method? You probably need to think about how you want {{ series_names }} to be output, rather than just calling the string representation of that variable. What you're generating at the moment is invalid Javascript - the console of your browser will probably reinforce this point.
Invalid number of parameters means one of your context variables, probably answer, was blank.
Your code is risky because Django will escape your context variables to be HTML safe, not JavaScript safe. One trick I use to get around this is to put all the parameters to a JS function in a dictionary, then convert it to JSON and use that for the context variable (using it with the |safe filter, and the <![CDATA[ markup in the template if needed).
As for show_chart not being resolved, you might want to make sure chart.js really is being loaded, and that it's not in a namespace of some form.

Categories