I'm using OpenLayers to create, display and edit features on the map. Features are saved as a JSONField in Django. Post Save I add a key django_pk to the JSON. How can I get this djanog_pk directly from the feature?
I need to do this so when the feature is edited, I know what feature to update in Django.
My JS code below:
<script>
var raster = new ol.layer.Tile({
source: new ol.source.OSM()
});
var source = new ol.source.Vector({wrapX: false});
var vector = new ol.layer.Vector({
source: source
});
var format = new ol.format.GeoJSON();
var select = new ol.interaction.Select({
wrapX: false
});
var modify = new ol.interaction.Modify({
features: select.getFeatures()
});
var map = new ol.Map({
interactions: ol.interaction.defaults().extend([select, modify]),
layers: [raster, vector],
target: 'map',
view: new ol.View({
center: [-11000000, 4600000],
zoom: 4
})
});
var features = new ol.source.Vector({
projection: 'EPSG:4326'
});
{% for polygon in polygons.0.gates %}
console.log(format.readFeature({{ polygon|safe }}).getProperties()))
{% endfor %}
features.addFeature(format.readFeature({{ polygons.0.protected_area|safe }}));
{% for polygon in polygons.0.gates %}
features.addFeature(format.readFeature({{ polygon|safe }}));
console.log(format.readFeature({{ polygon|safe }}))
{% endfor %}
var featureOverlay = new ol.layer.Vector({
source: features,
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)'
}),
stroke: new ol.style.Stroke({
color: '#ff78d1',
width: 2
}),
image: new ol.style.Circle({
radius: 6,
fill: new ol.style.Fill({
color: '#4ca6b6'
}),
})
})
});
featureOverlay.setMap(map);
</script>
I tried this: Buyt it only return geometry:
select.on('select', function(e) {
console.log(e.selected[0].getProperties())
});
The JSONField in Django looks like this:
{
"geometry":{
"type":"Polygon",
"coordinates":[
[
[
-11156543.033928039,
6698655.0485978
],
[
-11410925.464061106,
5896371.999716589
],
[
-9972686.33984723,
5084305.011214877
],
[
-9512841.177683609,
6649735.350495286
],
[
-10090093.61529326,
6972605.357971871
],
[
-11156543.033928039,
6698655.0485978
]
]
]
},
"type":"Feature",
"properties":null,
"django_pk":10
}
So I need to find the django_pk for a feature when editing it, it selecting it, ot deleting it.
Not sure how to get this information
Ok, I its actually simple.
You can read any property of the GeoJSON format:
select.on('select', function(e) {
console.log(e.selected[0].getProperties())
});
Select being:
var select = new ol.interaction.Select({
wrapX: false
});
And in my Django code I just do this on post_save:
#receiver(post_save, sender=ProtectedArea)
def update_json(sender, instance, created, **kwargs):
post_save.disconnect(update_json, sender=ProtectedArea)
try:
instance.polygone = literal_eval("%s" % instance.geojson_file.read())
except:
pass
if instance.polygone['properties'] == None:
instance.polygone['properties'] = {}
instance.polygone['properties']['pk'] = instance.pk
else:
instance.polygone['properties']['pk'] = instance.pk
instance.save()
post_save.connect(update_json, sender=ProtectedArea)
Related
How to show specific data on html page using chart.js and django i am trying this method i can see data api view but cannot see on chart. i am able to see data except my query set. Is there any doc for this. Please help me i am beginner in django,
Here is my Views.py
class secondapi(APIView):
authentication_classes = []
permission_classes = []
def get(self, request, format=None):
qs = Add.objects.all().aggregate(Sum('budget')) # here is problem
labels = ["sum", "Blue", "Yellow", "Green", "Purple", "Orange"]
default_items = [qs, 23, 2, 3, 12, 2]
data = {
"newlabels": labels,
"newdata": default_items,
}
return Response(data)
html page
<script>
var endpoint = '/api/chart/data/'
var labels = [] //
var defaultData = []; //
$.ajax({
method: "GET",
url: endpoint,
success: function(i){
labels = i.newlabels
defaultData = i.newdata
console.log(labels)
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels, // CHANGED
datasets: [{
label: '# of Votes',
data: defaultData, // CHANGED
}]
}
})
},
error: function(error_data){
console.log("error")
console.log(error_data)
}
})
</script>
<div class='col-sm-6'>
<canvas id="myChart"></canvas>
</div>
</body>
</html>
def get(self, request, format=None):
qs = Add.objects.all().aggregate(Sum('expense'))
# some = list(qs.keys())
a = qs.values()
labels = ["sum", "Blue", "Yellow", "Green", "Purple", "Orange"]
default_items = [a, 23, 2, 3, 12, 2]
data = {
"newlabels": labels,
"newdata": default_items,
}
return Response(data)
Trying to revive a Django app that was working 2014-2015 then was turned off for almost 3 years and now is not willing to cooperate.
Mac OS X el Capitan 10.11.6
Python 3.6 (also tried 3.4)
Django 1.8.3
In short, how does notation (in template) {% url 'item-jqgrid-entity1' pk=original.id %} connects to django models Item and Entity1 WITHOUT having item-jqgrid-entity1 listed in url.py ? I am getting
Reverse for 'item-jqgrid-entity1' with arguments '()' and
keyword arguments '{'pk': 123}' not found. 0 pattern(s) tried: []
and it used to work somehow. If I introduce matching URL in urls.py, it works, but I want to know how it was working without it.
For a given model (Item) the default template change_form.html was overriden. The custom one goes like this:
{% extends "admin/change_form.html" %}
{% load admin_urls %}
.
.
var searchable_columns = {
alteration_type: {
searchoptions: {
dataUrl: '{% url 'item-jqgrid-entity1' pk=original.id %}'
}
},
disease: {
searchoptions: {
dataUrl: '{% url 'item-jqgrid-entity2' pk=original.id %}'
}
},
}
.
.
$(document).ready( function () {
$("#table_{{ original.id }}").jqGrid({
autowidth: true,
height: 300,
hidegrid: false,
// double click handler
ondblClickRow: function(rowid, iRow, iCol, e) {
// rowid is object ID i want to edit
// mimics showRelatedObjectPopup()
// in django's RelatedObjectLookups.js
href = '{% url 'admin:some real url here' %}' + rowid + '/?_to_field=id&_popup=1';
$('div.alert').remove();
var win = window.open(href,
'id_drug',
'height=500,width=800,resizable=yes,scrollbars=yes');
win.focus();
return false;
},
// #25: workflow: marking edited rows
gridComplete: function () {
for (var i = 0; i < rowsToColor.length; i++) {
$("#" + rowsToColor[i]).find("td").css("background-color", "#dff0d8");
$("#" + rowsToColor[i]).find("td").css("color", "#468847");
}
// this will overwrite green ones, too.
for (var i = 0; i < incompleteRowsToColor.length; i++) {
$("#" + incompleteRowsToColor[i]).find("td").css("background-color", "#fcf8e3");
$("#" + incompleteRowsToColor[i]).find("td").css("color", "#b94a48");
}
// this will overwrite green and yellow ones, too.
for (var i = 0; i < unworthyRowsToColor.length; i++) {
$("#" + unworthyRowsToColor[i]).find("td").css("background-color", "#f2dede");
$("#" + unworthyRowsToColor[i]).find("td").css("color", "#b94a48");
}
// commented lines are bold.
for (var i = 0; i < commentedRowsToBold.length; i++) {
$("#" + commentedRowsToBold[i]).find("td").css("font-weight", "bold");
}
},
datatype: "json",
colModel: [
{
label: 'Entity1',
name: 'entity1',
width: 45,
// search options
stype: 'select',
searchoptions: searchable_columns.entity1.searchoptions,
editable: true,
edittype: 'select',
editoptions: {
dataUrl: '{% url 'editdata-AllEntity1' %}',
},
},
{
label: 'Entity2',
name: 'entity2',
width: 75,
// search options
stype: 'select',
searchoptions: searchable_columns.entity2.searchoptions,
editable: true,
edittype: 'select',
editoptions: {
dataUrl: '{% url 'editdata-allEntity2' %}',
},
],
viewrecords: true, // show the current page, data rang and total records on the toolbar
caption: "{{ original.pk }}: {{ original }}",
pager: "#tablePager_{{ original.id }}",
}
});
$('#table_{{ original.id }}').jqGrid('filterToolbar');
$('#table_{{ original.id }}').navGrid("#tablePager_{{ original.id }}", {
search: false, // show search button on the toolbar
add: false,
edit: false,
del: false,
refresh: true, position: "left", cloneToTop: true
},
I have this code
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.2.js"></script>
<script type="text/javascript" src="js/chart-js/Chart.js"></script>
<script type="text/javascript">
var data = [
{
value: 300,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red"
},
{
value: 50,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Green"
},
{
value: 100,
color: "#FDB45C",
highlight: "#FFC870",
label: "Yellow"
}
];
$(document).ready(
function () {
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx).Pie(data);
document.getElementById("canvas_link").src = document.getElementById("myChart").toDataURL();
}
);
</script>
</head>
<body>
<p>save as image</p>
<canvas id="myChart" width="400" height="400"></canvas>
<p>export to pdf</p>
</body>
I need create pdf export and add into image with gener graph. Berofe I must save render image. I try use method .toBase64Image() but I dont know have can I start.
My proceed
create canvas_link (.toDataUrl). After click save as image I can greate and upload image to server. Then I can generate pdf export (across mPDF) and to add imageto into export. This i can create, but I dont know create and upload image of graph to server.
I need more examples from http://www.chartjs.org/docs/
in that case you don't need to upload as an image.
you could put the result of the call to toDataUrl function in the value of a hidden field and send it in a form (with an iframe as target) or by an ajax call
use the following options in the chart
//new options var
var options = {
bezierCurve : false,
//animation: false
onAnimationComplete: done
};
//your code with a little modification
$(document).ready(
function () {
var ctx = document.getElementById("myChart").getContext("2d");
//use the previously defined "options" here!!!
var myNewChart = new Chart(ctx).Pie(data, options);
}
);
//callback function, called when the pie ends his animation
function done(){
//this part of your code was moved here to avoid that store an empty image
document.getElementById("canvas_link").src = document.getElementById("myChart").toDataURL();
var postdata={
file: document.getElementById("myChart").toDataURL()
}
$.post( "store.php", postdata)
.done(function( ret ) {
console.log( "Data status: Loaded successfully ");
})
.fail(function( ret ) {
console.log( "Data status: error ");
})
;
}
Reference: http://api.jquery.com/jquery.post/
in php you can handle the content in this way
// file: store.php
// Interpret data uri
$uriPhp = 'data://' . substr($file, 5);
// Get content
$binary = file_get_contents($uriPhp);
$file = 'uploads/charts/'. time() .'.png';
// Save image
file_put_contents($file, $binary);
Reference: https://github.com/nnnick/Chart.js/issues/99#issuecomment-75359927
As per the documentation, you can print or save graph by API calls;
Example
var chart = new CanvasJS.Chart("chartContainer", {
theme: "theme2",
title:{
text: "Print Chart using print() method"
},
data: [
{
type: "column",
dataPoints: [
{ label: "apple", y: 10 },
{ label: "orange", y: 15 },
{ label: "banana", y: 25 },
{ label: "mango", y: 30 },
{ label: "grape", y: 28 }
]
}
]
});
chart.render();
document.getElementById("printChart").addEventListener("click",function(){
chart.print();
//chart.exportChart({format: "jpg"});
});
I'm trying to place markers based on the latitude and longitude stored in a model on a Google Map using the API and HTML5 geolocation.
The issue is how to loop through the lat/lon info for each object stored within JavaScript tags using template keywords, which I don't believe can be done in Django.
I found a similar question here Adding Google Map Markers with DJango Template Tags in Javascript which I mildly modified and placed within a template – not a separate script file – but it doesn't seem to work:
function loadMarkers(){
{% for story in stories %}
var point = new google.maps.LatLng({{story.latitude}},{{story.longitude}});
var marker = new google.maps.Marker({
position: point,
map: map
});
{% endfor %}
}
Any insight on how to properly loop through items in a stored Django object with lat, lon info and place these on a Google Map using the API would be very appreciated.
I use django-geoposition to manage my geodata
from django.db import models
from geoposition.fields import GeopositionField
class Zone(models.Model):
name = models.CharField(max_length = 50 )
kuerzel = models.CharField(max_length = 3 )
kn_nr = models.CharField(max_length = 5 )
beschreibung = models.CharField(max_length = 300 )
adresse = models.CharField(max_length = 100 )
position = GeopositionField()
view.py
from geo.models import Zone
from django.shortcuts import render_to_response, get_object_or_404, redirect
def ShowZonen(request):
zone=Zone.objects.all()
return render_to_response('zonen.html', {"zone": zone})
def showZoneDetail(request, zone_id):
zone=Zone.objects.get(id=zone_id)
return render_to_response('zonendetail.html', {"zone": zone})
template
zonendetail.html
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
function initialize() {
var mapDiv = document.getElementById('map-canvas');
map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(48.208174,16.373819),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
google.maps.event.addListenerOnce(map, 'tilesloaded', addMarkers);
}
function addMarkers() {
{% for mark in zone %}
var point = new google.maps.LatLng({{mark.position.latitude}},{{mark.position.longitude}});
var image = '{{ STATIC_PREFIX }}'+ 'checkmark.png';
var marker = new google.maps.Marker({
position: point,
map: map,
icon: image,
url: 'http://172.16.0.101:8882/zone/' + {{mark.id}},
title: '{{ mark.id }}',
});
marker['infowindow'] = new google.maps.InfoWindow({
content: "<h1>{{mark.name}}</h1> <br> {{ mark.name }} <p> {{ mark.name }}",
});
google.maps.event.addListener(marker, 'click', function() {
//window.location.href = this.url;
this['infowindow'].open(map, this);
});
google.maps.event.addListener(marker, 'mouseover', function() {
// this['infowindow'].open(map, this);
});
google.maps.event.addListener(marker, 'mouseout', function() {
// this['infowindow'].close(map, this);
});
{% endfor %}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I'm baffled that this dataView is empty! I have this same setup working with images but it's not displaying here. Am I missing something? Thanks for your help.
json:
{rows:[{"noteid":"4","txid":"97","contactid":"38","displayname":"Jeb Hafkin","txdate":"08\/20\/2010","date":"12\/08\/2011","type":"Treatment Note","content":"new test<img src=\"..\/logos\/1912323619.jpg\">","subject":"Jeb's note","firstname":"Jeb","lastname":"Hafkin"},{"noteid":"6","txid":"0","contactid":"51","displayname":"Bill Hyyman","txdate":null,"date":"12\/12\/2011","type":"","content":"test","subject":"","firstname":"Bill","lastname":"Hyyman"}], "success": true}
data Store, tpl, dataview:
var noteStore = new Ext.data.Store({
reader: new Ext.data.JsonReader({
fields: ['noteid','txid','contactid', 'displayname', 'date',
'subject','txdate','type','amtpd','content' ],
root: 'rows',
id: 'noteid'
}),
proxy: new Ext.data.HttpProxy({
url: '/request.php?x=noteStore'
})
});
var tpl = new Ext.XTemplate (
'<tpl for ".">',
'<p class="note">noteid = {noteid} </p>',
'</tpl>'
);
var noteDataView = new Ext.DataView({
store: noteStore,
tpl: tpl,
autoHeight:true,
multiSelect: true,
overClass:'x-view-over',
itemSelector:'p.note',
emptyText: 'No notes to display'
});
var notePanel = new Ext.Panel ({
layout: 'fit',
padding: 10,
items: [noteDataView],
tbar: noteTb
});
The store needs to be loaded. Try adding autoLoad: true to your store:
var noteStore = new Ext.data.Store({
reader: new Ext.data.JsonReader({
fields: ['noteid','txid','contactid', 'displayname', 'date',
'subject','txdate','type','amtpd','content' ],
root: 'rows',
id: 'noteid',
}),
proxy: new Ext.data.HttpProxy({
url: '/request.php?x=noteStore'
}),
autoLoad: true
});