Bootstrap Typeahead basic example not working in Django - django

I am trying to implement Bootstrap Typeahead to eventually use an Elasticsearch instance I have, but I cannot even get the basic example to work in Django (2.2.6). I am taking the majority of this code from the examples page. Here is the HTML I am using:
typeahead.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>
<script type="text/javascript">
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};
};
var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California',
'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii',
'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',
'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',
'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',
'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',
'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',
'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
];
$('.typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'states',
source: substringMatcher(states)
});
</script>
</head>
<body>
<div id="the-basics">
<input class="typeahead" type="text" placeholder="States of USA">
</div>
</body>
</html>
Here is the page/URL I am trying to access:
urls.py
from django.urls import path
from . import views
app_name = 'materials'
urlpatterns = [
path('typeahead/', views.typeahead_view, name='typeahead')
]
And this is the basic view I have set up for this page:
views.py
def typeahead_view(request):
return render(request, 'materials/typeahead.html')
Nothing happens when I start typing in the input...

There is a problem with your html page. First of all, jquery was not added in it and secondly add all the js file at the end of the body. Check below updated code for the html file.
typeahead.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="the-basics">
<input class="typeahead" type="text" placeholder="States of USA">
</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>
<script type="text/javascript">
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};
};
var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California',
'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii',
'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',
'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',
'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',
'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',
'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',
'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
];
$('.typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'states',
source: substringMatcher(states)
});
</script>
</body>
</html>
It works properly. I hope this will help you :)

Related

Replacing values in kendo grid

I have a problem that I even have an idea where to start looking..
So I have a grid and a column of type of receipts. The values are numbers. How can I replace them with meaningfull values (if type is '0', then I need to display 'CASH'). What is the smartest way to do that?
Code:
<?php
require_once(__DIR__ . '/localization/taxesLocalization.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo $taxes ?></title>
<link rel="stylesheet" href="styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="styles/kendo.material.min.css" />
<link rel="stylesheet" href="css/custom_style.css">
<link rel="stylesheet" href="HtmlTemplates/notifications.php">
<script src="js/jquery.min.js"></script>
<script src="js/kendo.all.min.js"></script>
<script src="js/devices.js"></script>
<script src="js/functions.js"></script>
<script src="js/FCM.js"></script>
<script src="js/functions/confirm_window.js"></script>
<script src="js/MessageTypes/message_types.js"></script>
<script src="js/functions/show_notification.js"></script>
<script src="js/taxes_scripts/constants.js"></script>
<script src="js/taxes_scripts/functions.js"></script>
<script src="js/functions/duplicates_check.js"></script>
<script src="js/taxes_scripts/services.js"></script>
</head>
<body>
<nav>
<div id="toolbar"></div>
<?php include "navmenu.php"; ?>
</nav>
<span id="popupNotification"></span>
<br>
<div class="" style="width: 100%;">
<div>
<div id="device_container">
<label for="devices" ><b><?php echo $devices ?></b></label>
<input id="device-report" style="width: 270px" />
</div>
</div>
<br>
<div id="gridSession"></div>
<div id="grid"></div>
</div>
</body>
</html>
<script>
var device_ID = 510;
const X_SESSION = "./services/ReportsServices/getXSessionInfo.php?device_ID=";
$(document).ready(function () {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: X_SESSION + device_ID,
dataType: "json"
}
},
schema: {
data: "data",
model: {
id: "id",
fields: {
sequence: {},
datestart: {},
total: {},
type: {},
receipt_count: {},
from_ticket: {},
to_ticket: {},
date_start: {},
date_end: {}
}
}
}
});
var grid = $("#grid").kendoGrid({
dataSource: dataSource,
navigatable: true,
scrollable: true,
resizable: true,
sortable: true,
filterable: false,
height: $(document).height() - 120,
columns: [
{field: "sequence", title: "Slijed"},
{field: "datestart", title: "Početak sesije"},
{field: "total", title: "Ukupno na računu"},
{field: "type", title: "Način plačanja "},
{field: "receipt_count", title: "Broj računa"},
{field: "from_ticket", title: "Od kartice"},
{field: "to_ticket", title: "Do kartice"},
{field: "date_start", title: "Datum prvog računa"},
{field: "date_end", title: "Datum zadnjeg računa"}
]
}).data("kendoGrid");
$("#device-report").kendoComboBox(
);
});
</script>
You can use template on the grid column which will check the value of type and update the column field accordingly:
{field: "type", title: "Način plačanja", template: "#if (type == 0) {# CASH #} else {# Another value #}#"}
EDIT
Haven't used switch in a template column before but something like this should be pretty close:
{field: "type", title: "Način plačanja", template: "#var value; switch(type){ case 0: value = 'CASH'; break; case 1: value = 'Another value'; break; case 3: value = 'ANOTHER value'; break; default: value = 'Default value'; }##=value#"}

googlecharts error- Invalid row type for row 0

I am gettting this below error when i try to draw a line graph. i dont understand where i am doing wrong
ReferenceError: CAE is not defined
[ "January 16",CAE,18],
Nationa...ers.jsp (line 11, col 36)
Error: Invalid row type for row 0
Here is my code
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*" %>
<%# page import="java.io.*" %>
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
var theData = [ // Start of JavaScript data object
<%
Class.forName("oracle.jdbc.OracleDriver").newInstance();
String connectionURL = "someurl";
Connection connection = null;
connection = DriverManager.getConnection(connectionURL);
PreparedStatement ps = connection.prepareStatement("SELECT TRIM(TO_CHAR(order_date, 'Month')) ||' '|| TO_CHAR(order_date, 'yy') month, order_channel, total FROM ( SELECT order_date, order_channel, COUNT(*) total FROM order_channel WHERE order_date >= TO_DATE('01-Jan-2016', 'dd-Mon-yyyy') GROUP BY order_date, order_channel) ORDER BY TO_DATE(order_date), order_channel");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
%>
[ "<%= rs.getString(1)%>",<%= rs.getString(2)%>,<%= rs.getString(3)%>],
<%
};
// End of JavaScript object holding the data
%>
];
</script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:['corechart', 'Bar']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([['Month', 'OrderChannel', 'Total']].concat(theData), false);
var options = {
title: 'National Monthly Orders',
hAxis: {
title: 'Month of Orderdate'
},
vAxis: {
title: 'Distinct count'
},
legend:{position:'none'}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 1000px; height: 350px;"></div>
</body>
</html>
looks like the second column should be type: 'string'
try this...
["<%= rs.getString(1)%>", "<%= rs.getString(2)%>", <%= rs.getString(3)%>]
vs.
["<%= rs.getString(1)%>", <%= rs.getString(2)%>, <%= rs.getString(3)%>]

google chart get selected value

I am trying to get the selected value of a Google Table Chart. When the chart content is not filtered using the string filter, it returns the index of the selected row according to the DataTable, but when it is filtered using the string filter, it doesn't returns the correct issue.
To replicate the issue please do the following code
1. Run the below code
Select Aaron in the table. A message box will display its index as 5.
Type letter 'A' in the string filter. Now select the Aaron, it will return 0 which is a bug.
It should return the index of the row in the data table for 'Aaron' which is 5
<!DOCTYPE html>
<html>
<head>
<title>Google Developers</title>
<link rel="stylesheet" type="text/css" href="/_static/07491c0cdc/css/screen-docs.css" />
<link rel="stylesheet" href="http://www.google.com/cse/style/look/default.css" type="text/css" />
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:300,400" type="text/css">
<script src="/_static/07491c0cdc/js/prettify-bundle.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script id="jqueryui" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js" defer async></script>
<script src="http://www.google.com/jsapi?key=AIzaSyCZfHRnq7tigC-COeQRmoa9Cxr0vbrK6xw"></script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="/_static/07491c0cdc/js/framebox.js"></script>
</head>
<body class="docs slim framebox_body">
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="stringFilter_dashboard_div" style="border: 1px solid #ccc">
<div id="stringFilter_control_div" style="padding-left: 2em"></div>
<div id="stringFilter_chart_div"></div>
</div>
<script type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart', 'table', 'gauge', 'controls']});
google.setOnLoadCallback(apiLoaded);
function apiLoaded() {
drawStringFilter();
}
function drawStringFilter() {
var dashboard = new google.visualization.Dashboard(
document.getElementById('stringFilter_dashboard_div'));
var control = new google.visualization.ControlWrapper({
'controlType': 'StringFilter',
'containerId': 'stringFilter_control_div',
'options': {
'filterColumnIndex': 0
}
});
var chart = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'stringFilter_chart_div',
'options': {'height': '25em', 'width': '20em'}
});
google.visualization.events.addListener(chart,'select',tableSelectHandler);
function tableSelectHandler(){
var selectedItem = chart.getChart().getSelection()[0];
alert(selectedItem.row);
}
var data = google.visualization.arrayToDataTable([
['Name', 'Age'],
['Michael' , 12],
['Elisa', 20],
['Robert', 7],
['John', 54],
['Jessica', 22],
['Aaron', 3],
['Margareth', 42],
['Miranda', 33]
]);
dashboard.bind(control, chart);
dashboard.draw(data);
}
</script>
<script>
devsite.github.Link.convertAnchors();
window.prettyPrint();
</script>
</body>
</html>
This should work:
function tableSelectHandler(e){
var selectedItem = chart.getChart().getSelection()[0];
var true_selected = chart.getDataTable().getTableRowIndex(selectedItem.row)
alert(true_selected);
}
getTableRowIndex traces the row back to the datatable
Expanding on juvian's answer, you should test the selection length before trying to access any elements in the array, as the array may be empty (or contain multiple elements if more than one row is selected):
function tableSelectHandler(e){
var selection = chart.getChart().getSelection();
var dt = chart.getDataTable();
for (var i = 0; i < selection.length; i++) {
// colIndex is the index of the column you want to get data from
var value = dt.getValue(selection.row, colIndex);
}
}

Polymer if-template with filter: filter not updating

I am using an if-template to show or hide items in a list, within a Polymer-element.
My template is based on a list of values, and filtered using a reference list.
Updating the list of values yields the desired effect. However, changing the filter reference list (here removing one element) does not yield an update of the template.
<!DOCTYPE html>
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/polymer/0.2.3/platform.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/polymer/0.2.3/polymer.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<test-component></test-component>
</body>
</html>
<polymer-element name='test-component' attributes='itemlist filterlist'>
<template>
<style>
</style>
<table id='table'>
<tr template repeat="{{item in itemlist}}">
<template if="{{item | applyFilter(filterlist)}}">
<td>test</td>
</template>
</tr>
</table>
<input type='button' value='remove 1 element' on-click={{clicked}}></input>
<div id='msg'></div>
</template>
<script>
Polymer('test-component', {
itemlist: [1,2,3],
filterlist: [1,2],
applyFilter: function(item, filterlist) {
var test = false;
if (filterlist) {
filterlist.forEach(function(filteritem) {
test = test || ((new RegExp(filteritem)).test(item));
});
}
return test;
},
clicked: function() {
this.$.msg.innerHTML = 'Filter list was ' + this.filterlist;
this.filterlist.splice(1,1);
this.$.msg.innerHTML += ', now it\'s ' + this.filterlist;
}
});
See http://jsbin.com/vuvikare/4/edit?html,output for runnable code.
Is there a way to trigger this update (for example using filterChanged observer)?
Thanks
This is very much a hack, but I got it to work by adding this method:
filterlistChanged: function() {
Array.prototype.forEach.call(this.$.table.querySelectorAll('template[if]'), function(t) {
t.iterator_.updateIteratedValue();
});
},
Basically, it finds all the inner template elements in the table and forces them to update (using a private method).

Ext.On Ready () function not defined error in upload form . How to debug it?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title> Upload Layer - EtherSpat </title>
<form action="."
enctype="multipart/form-data" method="post">
<p>
Type some text (if you like):<br>
<input type="text" name="textline" size="30">
</p>
<p>
Upload a shp file:<br>
<input type="file" name="shp" size="40">
</p>
Upload a shx file:<br>
<input type="file" name="shx" size="40">
</p>
Upload a dbf file:<br>
<input type="file" name="prj" size="40">
</p>
Upload a dbf file:<br>
<input type="file" name="dbf" size="40">
</p>
<div>
<input type="submit" value="Send">
</div>
</form>
<link rel="stylesheet" type="text/css" href="../geodjango/geographic_admin/templates/ext-4.0.1
/ext-all.css" />
<script type="text/javascript" src="../geodjango/geographic_admin/templates/ext-4.0.1
/ext-all.js"></script>
<script src="http://demo.geonode.org/media/static/script/OpenLayers.js"></script>
<script type="text/javascript" src="/lang.js"></script>
<script type="text/javascript">
{% autoescape off %}
Ext.onReady(function(){
Ext.QuickTips.init();
var form_target = "{% url maps.views.upload_layer %}";
// var xml_unsafe = /([^a-zA-Z\._])/g;
var xml_safe = /([a-zA-Z]+_[a-zA-Z]+_[1-2]{1}[0-9]{3}_[a-zA-Z]+$)/g;
var layer_name = new Ext.form.TextField({
id: 'layer_name',
fieldLabel: gettext('Name'),
name: 'layer_name',
emptyText: gettext('Unique name for layer. Defaults to file name.'),
validator: function(name) {
if (name.search(xml_safe) == -1) {
return gettext("The layer name must follow a pattern. Statename_city_year_datatype");
} else {
return true;
}
},
allowBlank: false
});
var listeners = {
"fileselected": function(cmp, value) {
// remove the path from the filename - avoids C:/fakepath etc.
cmp.setValue(value.split(/[/\\]/).pop());
}
};
var base_file = new Ext.ux.form.FileUploadField({
id: 'base_file',
emptyText: gettext('Select a layer data file'),
fieldLabel: gettext('File'),
name: 'base_file',
allowBlank: false,
listeners: listeners
});
var dbf_file = new Ext.ux.form.FileUploadField({
id: 'dbf_file',
emptyText: gettext('Select a .dbf data file'),
fieldLabel: gettext('DBF'),
name: 'dbf_file',
allowBlank: false,
listeners: listeners
});
var shx_file = new Ext.ux.form.FileUploadField({
id: 'shx_file',
emptyText: gettext('Select a .shx data file'),
fieldLabel: gettext('SHX'),
name: 'shx_file',
allowBlank: false,
listeners: listeners
});
var prj_file = new Ext.ux.form.FileUploadField({
id: 'prj_file',
emptyText: gettext('Select a .prj data file (optional)'),
fieldLabel: gettext('PRJ'),
name: 'prj_file',
allowBlank: true,
listeners: listeners
});
var fp = new Ext.FormPanel({
renderTo: 'upload_form',
fileUpload: true,
width: 500,
frame: true,
title: gettext('Upload Layer Data'),
autoHeight: true,
bodyStyle: 'padding: 10px 10px 0 10px;',
labelWidth: 50,
defaults: {
anchor: '95%',
msgTarget: 'side'
},
items: [layer_name, base_file, dbf_file, shx_file, prj_file, {
xtype: "hidden",
name: "csrfmiddlewaretoken",
value: "{{ csrf_token }}"
}],
buttons: [{
text: gettext('Upload'),
handler: function(){
if (fp.getForm().isValid()) {
fp.getForm().submit({
url: form_target,
waitMsg: gettext('Uploading your data...'),
success: function(fp, o) {
document.location = o.result.redirect_to;
},
failure: function(fp, o) {
error_message = '<ul>';
for (var i = 0; i < o.result.errors.length; i++) {
error_message += '<li>' + o.result.errors[i] + '</li>'
}
error_message += '</ul>'
Ext.Msg.show({
title: gettext("Error"),
msg: error_message,
minWidth: 200,
modal: true,
icon: Ext.Msg.ERROR,
buttons: Ext.Msg.OK
});
}
});
}
}
}]
});
var disable_shapefile_inputs = function() {
dbf_file.disable();
dbf_file.el.parent('.x-form-item').hide();
shx_file.disable();
shx_file.el.parent('.x-form-item').hide();
prj_file.disable();
prj_file.el.parent('.x-form-item').hide();
};
var enable_shapefile_inputs = function() {
dbf_file.enable();
dbf_file.el.parent('.x-form-item').show();
shx_file.enable();
shx_file.el.parent('.x-form-item').show();
prj_file.enable();
prj_file.el.parent('.x-form-item').show();
};
var check_shapefile = function() {
var main_filename = base_file.getValue();
if (main_filename.search(/\.shp$/i) != -1) {
enable_shapefile_inputs();
}
else {
disable_shapefile_inputs();
}
};
base_file.addListener('fileselected', function(cmp, value) {
check_shapefile();
var main_filename = value.split(/[/\\]/).pop();
var extension_index = main_filename.search(/\.\w+$/i);
if (extension_index != -1 && layer_name.getValue() == "") {
var cleaned = main_filename.substring(0, extension_index);
cleaned = cleaned.replace(xml_safe, "_");
layer_name.setValue(cleaned);
}
});
disable_shapefile_inputs();
});
{% endautoescape %}
</script>
This is the code . I understand that I need to include ext-base.js , but there is no such file in the ext-4 package that I have downloaded . Is there a certain path I need to follow , as in the files need to be in a certain directory for it to work in Django ? This html file is in the templates folder and the ext-4 folder too is in the templates folder
Javascript and js files should be in your "media" (Django <= 1.2) or "static" (Django 1.3) folders.
Django 1.3: https://docs.djangoproject.com/en/1.3/howto/static-files/#basic-usage
Put your js files in your app static/js/ folder and use this in your template:
<script src="{{STATIC_URL}}js/foo.js">
Django 1.2: In your settings.py add:
MEDIA_URL = '/static/'
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = '%s/static/' % BASE_DIR
Put your js files in your project static/js/ folder and use this in your template:
<script src="{{MEDIA_URL}}js/foo.js">
Be sure to configure your production web server properly as well: https://docs.djangoproject.com/en/dev/howto/deployment/modwsgi/#serving-media-files