showing all fields in a Dojo Data Grid with dojo.store.JsonRest - django

I have a Dojo Data Grid for displaying contact information that is showing values for only two columns: "model" and "pk". The other columns are blank, probably because the JSON response from the server puts the other name/value pairs inside of "fields":
[{"pk": 1, "model": "accounting.contacts", "fields": {"mail_name": "Andy", "city": "Grand Rapids", "zip": "49546", "country": "US", "state": "MI"}}]
What is the best way to get all my fields to show up in the grid?
Here's the relevant view in Django:
def contacts(request):
json_serializer = serializers.get_serializer("json")()
json_contacts = json_serializer.serialize(Contacts.objects.all(), ensure_ascii=False)
return HttpResponse(json_contacts, mimetype="application/json")
And here's my Dojo page:
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js"
data-dojo-config="isDebug: true,parseOnLoad: true">
</script>
<script type="text/javascript">
dojo.require("dojo.store.JsonRest");
dojo.require("dojox.grid.DataGrid");
dojo.require("dojo.data.ObjectStore");
dojo.ready(function(){
objectStore = new dojo.store.JsonRest({target:"/contacts/"});
//alert(objectStore);
dataStore = new dojo.data.ObjectStore({objectStore: objectStore});
//alert(dataStore);
layoutGridContacts = [{
field: 'mail_name',
name: 'Name',
width: '200px'
},
{
field: 'model',
name: 'DB Table',
width: '100px'
...
}];
gridContacts = new dojox.grid.DataGrid({
query: {
name: '*'
},
store: dataStore,
clientSort: true,
structure: layoutGridContacts
}, dojo.byId("containerGridContacts"));
gridContacts.startup();
});
</script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dijit/themes/claro/claro.css" />
<style type="text/css">
#import "http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojox/grid/resources/Grid.css";
#import "http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojox/grid/resources/claroGrid.css";
.dojoxGrid table {margin: 0; } html, body { width: 100%; height: 100%;
margin: 0;}
</style>
</head>
<body class="claro">
<div id="containerGridContacts" style="width: 100%, height: 100%;">
</div>
</body>
Thanks.

This is really a question of, "How do I interact with a javascript object?" Given the JSON in your question, and assuming you assigned it to the variable obj, you could access mail_name with obj[0]['fields']['mail_name'] or using dot notation, obj[0].fields.mail_name. I haven't used Dojo, but I'd wager you just need to set fields.mail_name as the field in layoutGridContacts.

I was able to get the server to produce a JSON response that does not contain nested objects, so the Dojo Store was able to use it. To do this I changed my view to:
def contacts(request):
all_contacts = list(iter(Contacts.objects.values()))
json_contacts = simplejson.dumps(all_contacts)
return HttpResponse(json_contacts, mimetype="application/json")

Use "fields." in front of your field identifier to access the properties inside fields:
layoutGridContacts = [{
field: 'fields.mail_name',
name: 'Name',
width: '200px'
},
...

You can use formatter method to retrieve the data. For your example it will be something like below
{name:"Name",
field: "fields",
width: "20%",
cellStyles:"background-color:#e3690b;",
formatter: function(field){
if(!field){return;}
return field.mail_name;
}
}

Related

Is it possible to highlight some states of US and some states of Canada in GeoChart?

Region 1
Region 2
I am trying to add map on a location page and I want to select some states from US and Canada in different regions when user hovers on a specific part of the map. Basically a map of North and South America(Brazil and Argentina) with different regions.
In the following code I attempted to highlight 2 US states and 1 Canada state. But I get "Requested map does not exist" error when I try to highlight states on a continent.
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {
'packages': ['geochart'],
'mapsApiKey': 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'
});
google.charts.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['State', 'Offices'],
['New Jersey', 2],
['Alabama', 3],
['Toronto', 1]
]);
var options = {
region: '019', // Americas Continent
colorAxis: {
colors: ['#00853f', 'black', '#e31b23']
},
backgroundColor: '#81d4fa',
datalessRegionColor: 'gray',
defaultColor: '#f5f5f5',
resolution: 'provinces'
};
var chart = new google.visualization.GeoChart(document.getElementById('geochart-colors'));
chart.draw(data, options);
};
</script>
</head>
<body>
<div id="geochart-colors" style="width: 100%; height: 100%;"></div>
</body>
</html>
Is it possible to do so? How can I achieve something like the image attached?
I would really appreciate your time and help. Thank you!

Django Fullcalendar - More than one calendar in App

Sice i managed to implement Fullcalendar's functionality into my Django app, I have another question.
Is it possible to render more than one Fullcalendar into my html page, depending of how many Calendars are made inside the database. And, i need them to be rendered HORIZONTALLY.
I suppose that i need to change my div's id to 'calendar2' for example. But what should i change inside the initializer?
This is full script and style from my calendar.
<script>
document.addEventListener('DOMContentLoaded', function () {
let calendarEl = document.getElementById('calendar');
let calendar = new FullCalendar.Calendar(calendarEl, {
minTime: "07:00:00",
maxTime: "22:00:00",
businessHours: {
startTime: '08:00', // a start time (10am in this example)
endTime: '21:00', // an end time (6pm in this example)
},
height: 'auto',
locale: 'sr',
plugins: ['dayGrid', 'timeGrid', 'list', 'interaction'],
defaultView: 'timeGridDay',
header: {
left: 'today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
},
navLinks: false, // can click day/week names to navigate views
editable: false,
eventLimit: true, // allow "more" link when too many events
events: [
{% for i in events %}
{
title: "{{ i.event_name}}",
start: '{{ i.start_date|date:"Y-m-d" }}T{{ i.start_date|time:"H:i" }}',
end: '{{ i.end_date|date:"Y-m-d" }}T{{ i.end_date|time:"H:i" }}',
},
{% endfor %}
]
});
calendar.render();
});
</script>
<style>
body {
margin: 40px 10px;
padding: 0;
font-family: Arial, Helvetica Neue, Helvetica, sans-serif;
font-size: 14px;
}
#calendar {
max-width: 900px;
margin: 0 auto;
}
</style>
<body>
<div id='calendar'></div>
</body>
I'll pass the answer from the comment section.
Just create as many div elements as you need, and attach a calendar to each one (let calendarEl = document.getElementById('calendar'); controls which element the calendar is attached to, so you just need that to be dynamic, or repeated).
And flex style helped me to put the next to each other, horizontally

"uncaught Syntax error: unexpected token {" when exporting JSON content to bootstrap table script

I am trying to convert data under django pandas dataframe to json and then to table using pandas_bootstrap_table.
The error in browser console is "uncaught Syntax error: unexpected token {"
Here is my view function
def productview(request):
qs = npmargin.objects.filter(user=selected_user)
df = convert_to_dataframe(qs, fields=['gross_profit_margin_2015',])
json = df.to_json(orient='records')
context = {
"data": "json"
}
return render (request, 'operating/chart2.html', context)
Below is charts2.html
{% load static %}
<script src="{%static "js/bootstrap.min.js"%}"></script>
<script src="{%static "js/jquery-slim.min.js"%}"></script>
<script src="{%static "js/bootstrap-table.js"%}"></script>
<script src="{%static "js/pandas_bootstrap_table.js"%}"></script>
<table id='datatable'></table>
The Json data from the above view function is sent to pandas_boostrap_table.js. The browser shows the unexpected token "{" error at the data:{{data|safe}}
$(document).ready(function(){
$('#datatable').bootstrapTable({
striped: true,
pagination: true,
showColumns: true,
showToggle: true,
showExport: true,
sortable: true,
paginationVAlign: 'both',
pageSize: 25,
pageList: [10, 25, 50, 100, 'ALL'],
data:{{data|safe}}, //"The browser console shows error here"
});
});
The code in js/pandas_bootstrap_table.js isn't being parsed by the Django templating engine. The means {{ data|safe }} isn't being substituted with the data value from the view.
You'll want to move the code from pandas_bootstrap_table.js to someplace where the Django templating engine will substitute the value of data with its actual contents. Something to the effect of:
# views.py
def productview(request):
qs = npmargin.objects.filter(user=selected_user)
df = convert_to_dataframe(qs, fields=['gross_profit_margin_2015',])
json = df.to_json(orient='records')
context = {
"data": json # be sure to remove the quotes around json
}
return render (request, 'operating/chart2.html', context)
# chart2.html
{% load static %}
<script src="{%static "js/jquery-slim.min.js"%}"></script>
<script src="{%static "js/bootstrap.min.js"%}"></script>
<script src="{%static "js/bootstrap-table.js"%}"></script>
<table id='datatable'></table>
<script>
$(document).ready(function(){
$('#datatable').bootstrapTable({
striped: true,
pagination: true,
showColumns: true,
showToggle: true,
showExport: true,
sortable: true,
paginationVAlign: 'both',
pageSize: 25,
pageList: [10, 25, 50, 100, 'ALL'],
data: {{data|safe}}, // view source in your browser to see the value of data being printed out
});
});
</script>

Create a map of Canada and USA with Datamaps in a single page

I am using Datamaps to create a map of Canada and USA. I saw the tutorial and/or examples in its website and I saw a "USA map only" example. And I did that:
<script>
var addUSA = new Datamap({
scope: 'usa',
element: document.getElementById('usa-map'),
geographyConfig: {
highlightOnHover: false,
borderColor: '#006298',
borderWidth: 0.8,
popupTemplate: function(geography, data) {
return "<div class='hoverinfo'><strong>" + data.info + "</strong></div>";
}
},
dataUrl: 'data.json',
dataType: 'json',
data: {},
fills: {
defaultFill: '#FFFFFF'
}
});
addUSA.labels();
</script>
So I assume that you can also create a "Canada map only". But the problem is, I don't know how to combine two countries.
I aim for labels, the hover-info and json that's why I'm using Datamaps.
So I've found this URL entitled Custom Map Data in Datamaps by Mark DiMarco and I used and tried copying what he had done. On that link, he created a map of Afghanistan which was not included in his main examples on Datamaps website. But instead of one country, we will combine two countries custom map using Datamaps. This is an experiment I've made but I hope this will be the answer to your problem
First, he created a custom topo json for Afghanistan. He published a tutorial on how to create custom map data but I think I don't have an access 'cause I'm getting 404 or he took it down. Going back, the code he used for that custom topo json can also be found in his other works located at "More Versions" link in Datamaps website. You just need to look for the country/ies you need to make a custom topo json. On your end, look for datamaps.afg.js and datamaps.usa.js; and get the json.
I only have 1 reputation and I am limit with two URLs. Just visit this GitHub site where I put those two custom topo json for Canada and USA.
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Canada and USA</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script src="http://rawgithub.com/markmarkoh/datamaps/master/dist/datamaps.none.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<!-- CANADA -->
<h1>CANADA</h1>
<div id="canada"></div>
<!-- USA -->
<h1>USA</h1>
<div id="usa"></div>
</body>
</html>
CSS
#canada {
border: 1px solid #000000;
height: 450px;
width: 400px;
}
#usa {
border: 2px solid #EDA552;
height: 400px;
width: 500px;
}
JQUERY
$(function() {
var canadaMap = new Datamap({
element: document.getElementById('canada'),
geographyConfig: {
dataUrl: 'canada.topo.json'
},
scope: 'canada',
fills: {
defaultFill: '#bada55'
},
setProjection: function(element) {
var projection = d3.geo.mercator()
.center([-95, 71])
.scale(200)
.translate([element.offsetWidth / 2, element.offsetHeight / 2]);
var path = d3.geo.path().projection(projection);
return {path: path, projection: projection};
}
});
var USAmap = new Datamap({
element: document.getElementById('usa'),
geographyConfig: {
dataUrl: 'usa.topo.json'
},
scope: 'usa',
fills: {
defaultFill: '#bada55'
},
setProjection: function(element) {
var projection = d3.geo.mercator()
.center([-120, 54])
.scale(250)
.translate([element.offsetWidth / 2, element.offsetHeight / 2]);
var path = d3.geo.path().projection(projection);
return {path: path, projection: projection};
}
});
});
Working code here => JS FIDDLE

Django: fullcalendar weeknumber

I try to display week numbers but nothing happens
I put weeknumber in the javascript file
$(document).ready(function() {
$('#calendar').fullCalendar({
weekNumbers: true,
height:400,
header: {
left: 'prev,next today, save',
center: 'title',
right: 'month,agendaWeek,agendaDay,agendaFourDay'
},
'defaultView': 'month',
editable: true,
.....
what is this problem ?
Did you import necessary CSS and js for it ?
<link rel='stylesheet' href='fullcalendar/fullcalendar.css' />
<script src='lib/jquery.min.js'></script>
<script src='lib/moment.min.js'></script>
<script src='fullcalendar/fullcalendar.js'></script>
moreover
weekNumbers:
If set to true, week numbers will be displayed in a separate left column in the month/basic views as well as at the top-left corner of the agenda views. See Available views