how to render jsonresponse to template in django 1.9 - json

I want to render geojson data on map and want to show pop up when user clicks on marker. Below is the code in views.py
def extract_raster_points(request):
conn = psycopg2.connect(dbname="geodjango",host='localhost',user='postgres', password='postgres', port=5433)
cur=conn.cursor()
dict_cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
res=dict_cur.execute("""SELECT row_to_json(fc) FROM ( SELECT 'FeatureCollection' As type, array_to_json(array_agg(f)) As features FROM (SELECT 'Feature' As type, ST_AsGeoJSON(lg.geom)::json As geometry ,row_to_json((SELECT l FROM (SELECT id, species,rastvalues) As l )) As properties FROM pft_account As lg ) As f ) As fc;""")
points=dict_cur.fetchone()
#datapot = json.loads(str(points))
datapot = json.loads(json.dumps(points))
datapotg=datapot[0]
print(datapotg)
return JsonResponse(datapotg,safe=False)
models.py
class Account(models.Model):
#spid = models.AutoField(primary_key=True)
species=models.CharField(max_length=255)
x=models.FloatField()
y=models.FloatField()
last_modified = models.DateTimeField(auto_now = True)
first_created = models.DateTimeField(auto_now_add = True)
geom = models.PointField(srid=4326)
rastvalues=models.IntegerField()
objects=models.GeoManager()
def __str__(self):
return "%s %s %s %s" % (self.species, self.geom.x, self.geom.y, self.rastvalues)
urls.py
url(r'^potpft.data/$', extract_raster_points, name='extract_raster_points'),
url(r'^data.data/$', GeoJSONLayerView.as_view(model=Account), name='datapotg'),
pot_pft.html(Javascript code)
<script type="text/javascript" >
function main_map_init (map, options) {
var promise = $.getJSON('{% url "datapotg" %}');
// Download GeoJSON via Ajax
promise.then(function(data) {
var allbusinesses = L.geoJson(data);
var cafes = L.geoJson(data, {
filter: function(feature) {
return feature.properties.rastvalues == "3";
},
pointToLayer: function(feature, latlng) {
return L.marker(latlng, {
}).on('mouseover', function() {
this.bindPopup(feature.properties.model["rastvalues"]).openPopup();
});
}
});
var others = L.geoJson(data, {
filter: function(feature) {
return feature.properties.rastvalues != "3";
},
pointToLayer: function(feature, latlng) {
return L.marker(latlng, {
}).on('mouseover', function() {
this.bindPopup(feature.properties.model["rastvalues"]).openPopup();
});
}
});
map.fitBounds(allbusinesses.getBounds(), {
padding: [50, 50]
});
cafes.addTo(map)
others.addTo(map)
});
}
</script>
How can I render jsonresponse to template i.e(pft_pot.html)?

Related

For loop returning only first json Object Flutter

While I tried to fetch data from a JSON am only able to return the first object.
I had mentioned the statement which I think the issue is. I want to return all the available object from the JSON so that I shall display it in a list of cards. I need to return all the JSON objects and pass it to another page containing list of cards. If anyone knows the solution please help me fix it.
Thanks in advance.
import 'dart: convert';
import 'package:flutter/cupertino.dart';
import 'package:tts/tts.dart';
import 'package:wiizboo/service/Chatmsg_service.dart';
import 'package:wiizboo/widget/a%20copy.dart';
import 'package:wiizboo/widget/chat_in_message.dart';
import 'package:wiizboo/widget/chat_out_message.dart';
import 'package:wiizboo/widget/form.dart';
import 'package:wiizboo/widget/image_camera.dart';
import 'package:wiizboo/widget/image_gallery.dart';
class ChatMessageModel with ChangeNotifier {
String data;
List accntdet;
ChatmessageService chatservice = ChatmessageService();
List<Widget> messages = <Widget>[];
ChatMessageModel() {
sendMsg("Hi");
}
Future handlesubmission(String chattext) {
Widget message = new ChatInMessage(
text: chattext,
name: "Me",
type: true,
);
addMsg(message);
sendMsg(chattext);
}
addMsg(Widget msg) {
messages.insert(0, msg);
notifyListeners();
}
sendMsg(String msg) {
chatservice.SendMsg(msg).then((String msg) {
responseBuilder(msg);
});
}
responseBuilder(String msg) {
Widget message;
String identifier = '';
var arr = msg.split("~");
if (arr.length > 1) {
identifier = arr[0];
msg = arr[1];
} else {
msg = arr[0];
}
switch (identifier) {
case 'email_phone':
message = new Forms(onSubmitted: (String val) {
Widget a = new ChatInMessage(
text: val,
name: "Me",
type: true,
);
addMsg(a);
sendMsg(val);
});
break;
case 'selfie':
message = new ImageCamera(onSubmitted: (String imageres) {
Widget b = new ChatInMessage(
text: imageres,
name: "Me",
type: true,
);
sendMsg(imageres);
});
break;
case 'aadhar':
message = new ImageGalery(onSubmitted: (String imageres) {
Widget b = new ChatInMessage(
text: imageres,
name: "Me",
type: true,
);
sendMsg(imageres);
});
break;
case 'account_info':
print(msg);
data = msg;
String receivedJson = data;
List<dynamic> list = json.decode(receivedJson);
accntdet = list;
int l = list.length;
print(l);
//------------ the statement --------//
for (dynamic account in accntdet) {
message = new AccountInfo(
l: l,
iban: account['ibn_no'],
accno: account['account_no'],
sort: account['sort-code'],
currency: account['currency'],
);
}
//----------//
print(message);
break;
default:
message = new ChatOutMessage(
text: msg,
name: "WzBoo..",
);
Tts.speak(msg);
}
addMsg(message);
}
}
Change this bloc
class ChatMessageModel with ChangeNotifier {
String data;
List accntdet;
ChatmessageService chatservice = ChatmessageService();
List<Widget> messages = <Widget>[];
ChatMessageModel() {
sendMsg("Hi");
}
Future handlesubmission(String chattext) {
Widget message = new ChatInMessage(
text: chattext,
name: "Me",
type: true,
);
addMsg(message);
sendMsg(chattext);
}
addMsg(Widget msg) {
messages.insert(0, msg);
notifyListeners();
}
sendMsg(String msg) {
chatservice.SendMsg(msg).then((String msg) {
responseBuilder(msg);
});
}
responseBuilder(String msg) {
Widget message;
String identifier = '';
var arr = msg.split("~");
if (arr.length > 1) {
identifier = arr[0];
msg = arr[1];
} else {
msg = arr[0];
}
switch (identifier) {
case 'email_phone':
message = new Forms(onSubmitted: (String val) {
Widget a = new ChatInMessage(
text: val,
name: "Me",
type: true,
);
addMsg(a);
sendMsg(val);
});
break;
case 'selfie':
message = new ImageCamera(onSubmitted: (String imageres) {
Widget b = new ChatInMessage(
text: imageres,
name: "Me",
type: true,
);
sendMsg(imageres);
});
addMsg(message);
break;
case 'aadhar':
message = new ImageGalery(onSubmitted: (String imageres) {
Widget b = new ChatInMessage(
text: imageres,
name: "Me",
type: true,
);
sendMsg(imageres);
});
break;
case 'account_info':
print(msg);
data = msg;
String receivedJson = data;
List<dynamic> list = json.decode(receivedJson);
accntdet = list;
int l = list.length;
print(l);
//------------ the statement --------//
for (dynamic account in accntdet) {
message = new AccountInfo(
l: l,
iban: account['ibn_no'],
accno: account['account_no'],
sort: account['sort-code'],
currency: account['currency'],
);
print(message);
addMsg(message);
}
//----------//
break;
default:
message = new ChatOutMessage(
text: msg,
name: "WzBoo..",
);
Tts.speak(msg);
addMsg(message);
}
}
}

Autodesk Forge setNodeOff turns all nodes off

When I pass an array of dbIds to be turned off the viewer is turning every node off in my model.
Autodesk.Viewing.Viewer3D.prototype.turnOff = function(dbIds) {
var node;
$(dbIds)
.each(function(index, item) {
node = viewer.model.getData().instanceTree.nodeAccess.nodes[item];
viewer.impl.visibilityManager.setNodeOff(node, true);
});
}
If you pass the id of a parent, it will turn off all its children, which is probably what happens in your case. Turning nodes off definitely works fine, you can take a look at my demo at https://forge-rcdb.autodesk.io.
Select a row in the database view or a segment in the pie chart:
What you need to do is to get the leaf node ids, only leaf nodes are represented by geometry in the viewer.
Here is some ES6 code sample, extracted from there:
static getLeafNodes (model, dbIds) {
return new Promise((resolve, reject)=>{
try {
const instanceTree = model.getData().instanceTree
dbIds = dbIds || instanceTree.getRootId()
const dbIdArray = Array.isArray(dbIds) ? dbIds : [dbIds]
let leafIds = []
const getLeafNodesRec = (id) => {
var childCount = 0;
instanceTree.enumNodeChildren(id, (childId) => {
getLeafNodesRec(childId)
++childCount
})
if (childCount == 0) {
leafIds.push(id)
}
}
for (var i = 0; i < dbIdArray.length; ++i) {
getLeafNodesRec(dbIdArray[i])
}
return resolve(leafIds)
} catch(ex){
return reject(ex)
}
})
}
static async isolateFull (viewer, dbIds = [], model = null) {
try {
model = model || viewer.activeModel || viewer.model
viewer.isolate(dbIds)
const targetIds = Array.isArray(dbIds) ? dbIds : [dbIds]
const targetLeafIds = await ViewerToolkit.getLeafNodes(
model, targetIds)
const leafIds = await ViewerToolkit.getLeafNodes (model)
const leafTasks = leafIds.map((dbId) => {
return new Promise((resolveLeaf) => {
const show = !targetLeafIds.length ||
targetLeafIds.indexOf(dbId) > -1
viewer.impl.visibilityManager.setNodeOff(
dbId, !show)
resolveLeaf()
})
})
return Promise.all(leafTasks)
} catch (ex) {
return Promise.reject(ex)
}
}

Pusher not recognizing Auth data

I am trying to generate a Pusher authentication string. https://pusher.com/docs/auth_signatures. In my Django view, The response is a JSON string with an auth property just as it asked for.
{u'auth': u'1019dcd6d219db50d37e:926260b960edf94509e0fd86547ec756cc4a1006baef4e0b3f8ec35c1e7b8c05'}
but I am getting this error.
Pusher : Error : {"type":"WebSocketError","error":{"type":"PusherError","data":{"code":null,"message":"Auth info required to subscribe to private-account-313"}}}
Is the JSON formatted incorrectly, or does the issues lie somewhere else ? couldn't find anything on it on Pusher's website.
def pusher_auth(request):
# """ -Pusher private channel authentication
# Docs: https//pusher.com/docs/authenticating_users
# """
if request.method == 'POST':
user = request.user
socket_id = request.POST['socket_id']
channel = request.POST['channel_name']
if not (socket_id or channel or user):
raise Exception("Permission denied.")
fragments = channel.split('-')
resource = fragments[1]
resource_id = int(fragments[2])
account = Account.objects.get(email=user.email)
pusher_client = Pusher(app_id='199731', key='1019dcd6d219db50d37e', secret='9550fb09aacce399eeb6',
cluster='ap1', ssl=True)
auth = pusher_client.authenticate(channel, socket_id)
try:
if resource == 'account' and (account.id == resource_id):
print(auth)
context = auth
return composeJsonResponse(200, "", context)
else:
return {'nope'}
except:
raise Exception("Permission denied.")
The angular code where channel is being subscribed to
/**
* pusher-js wrapper as a factory.
* Docs: https://github.com/pusher/pusher-js
*/
(function () {
'use strict';
$pusher.$inject = ["Config"];
angular
.module('app.common')
.factory('$pusher', $pusher);
/** ngInject */
function $pusher(Config) {
var self = this;
self.client = new Pusher(Config.pusher.key, Config.pusher.options || {});
return {
client: self.client
};
}
})();
(function () {
'use strict';
angular
.module('app.core')
.constant('Config', getConfig());
function getConfig() {
return {
api_path: '',
pusher: {
// TODO: add environment-based configs values.
key: '1019dcd6d219db50d37e',
options: {
encrypted: true
}
}
};
}
})();
/**
* Subscribes to user's Pusher channel and binds callback events.
*/
function bindPusher() {
var defer = $q.defer();
var channelName = 'private-account-' + Session.account.id;
var channel = $pusher.client.subscribe(channelName);
channel.bind('pusher:subscription_succeeded', function (data) {
$log.debug('Pusher subscribed: ' + channel.name);
PushListener.bindAndListen(channel);
defer.resolve(data);
});
channel.bind('pusher:subscription_error', function (status) {
if (status === 403) {
var msg = 'Pusher channel not authorized.';
$log.warn(msg);
defer.reject(msg);
}
});
return defer.promise;
}

Angularjs ajax request in Symfony2 and Doctrine json response with relationships

I am trying to work with Symfony2, Doctrine and Angujarjs. There is no problem with Symfony2 or Doctrine but I have issues using an ajax request with angularjs. Either it doesn't load anything and I did make a mistake while loading the json (json comes from Symfony and its working) or if it's working, but the json doesn't contain any of the relationship's data.
So, what's the correct way to
A: create a response for angularjs with relationship data (such as articles and categories)
B: load the requested json into an angularjs variable
Here is my controller.js
var app = angular.module("MyApp", []) .config(['$interpolateProvider', function ($interpolateProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
}]);
app.filter('offset', function() {
return function(input, start) {
start = parseInt(start, 10);
return input.slice(start);
};
});
app.filter('htmlToPlaintext', function() {
return function(text) {
return String(text).replace(/<[^>]+>/gm, '');
};
});
app.controller("PaginationCtrl", function($scope, $http) {
$scope.articlesPerPage = 8;
$scope.currentPage = 0;
function htmlToPlaintext(text) {
return String(text).replace(/<[^>]+>/gm, '');
}
// this should load the json from '/admin/jsonallarticles' into the articles variable
$http.get('/admin/jsonallarticles').success(function(data) {
$scope.articles = data;
});
$scope.range = function() {
var rangeSize = 5;
var ret = [];
var start;
start = $scope.currentPage;
if ( start > $scope.pageCount()-rangeSize ) {
start = $scope.pageCount()-rangeSize+1;
}
for (var i=start; i<start+rangeSize; i++) {
ret.push(i);
}
return ret;
};
$scope.prevPage = function() {
if ($scope.currentPage > 0) {
$scope.currentPage--;
}
};
$scope.prevPageDisabled = function() {
return $scope.currentPage === 0 ? "disabled" : "";
};
$scope.pageCount = function() {
return Math.ceil($scope.articles.length/$scope.articlesPerPage)-1;
};
$scope.nextPage = function() {
if ($scope.currentPage < $scope.pageCount()) {
$scope.currentPage++;
}
};
$scope.nextPageDisabled = function() {
return $scope.currentPage === $scope.pageCount() ? "disabled" : "";
};
$scope.setPage = function(n) {
$scope.currentPage = n;
};
});
This is my symfony2 function
public function jsonallarticlesAction() {
$articles = $this->getDoctrine()
->getRepository('AcmeBlogBundle:Articles');
if ( !$articles ) {
throw $this->createNotFoundException(
'Keine Beiträge gefunden!');
}
$queryArticles = $articles->createQueryBuilder('a')
->where('a.status = :status')
->setParameter('status', 0)
->orderBy('a.createdDate', 'DESC')
->getQuery()
->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);;
$articles = array_values($queryArticles);
$response = new Response();
$response->setContent(json_encode($articles));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
EDITED CONTROLLER
I tried using the serializer which comes with Symfony
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new GetSetMethodNormalizer());
$serializer = new Serializer($normalizers, $encoders);
$articles = $this->getDoctrine()
->getRepository('AcmeBlogBundle:Articles')
->findAll();
if ( !$articles ) {
throw $this->createNotFoundException(
'Keine Artikel gefunden!');
}
$serializer->serialize($articles, 'json');
return new Response(json_encode($json));
But I receive an error:
A circular reference has been detected (configured limit: 1).
For work with Angular.js you must write Rest API. For this you can use https://github.com/FriendsOfSymfony/FOSRestBundle
And for serialize your entities with needed data use http://jmsyst.com/bundles/JMSSerializerBundle
It compatible with FOSRestBundle.
As example of use those bundles you can look one our project https://github.com/stfalcon-studio/lost-and-found
I ran into the same issue and it was due to the fact that my Entity was related back to the same entity from my second entity on a different field. I just simply created this function in my Entity:
public function removeRelationsThatCauseCircularError()
{
$this->companyEvents = NULL;
}
And run the function before going through the serializer.

Passing selected value of dropdownlist to a controller after postback

How to pass the selected value of a drop down list from view to controller after postback. As i'm new to the MVC architecture any help will be greatly appreciated. Thanks in advance.
I need to filter data based on the values of dropdown list. But when i move to the next page of pagedlist then all my dropdown list's value is set to default value.
Controller
public ActionResult ViewDataOfDatabase(string sortorder, string currentFilter, string searchString, int? page,FormCollection collection)
{
CCIRepository _repository = CCIRepository.CreateRepository();
AirtelManagementModel _Airtelmodel = new AirtelManagementModel();
IEnumerable<CityListClass> CityList = _repository.GetCities();
IEnumerable<SelectListItem> CityNames = from c in CityList
select new SelectListItem()
{
Value = c.CityName.ToString(),
Text = c.CityName.ToString(),
Selected = c.CityName == Request["CityNames"],
};
ViewBag.CityList = CityNames;
IEnumerable<clsYearOfDate> SelectList = GetYears();
//IEnumerable<MonthListClass> SelectMonthList = GetMonths(YearId);
IEnumerable<SelectListItem> Yearitems = (from v in SelectList
select new SelectListItem()
{
Value = v.YearSelectedId.ToString(),
Text = v.YearOfDate.ToString(),
Selected = v.YearOfDate == Request["Yearitems"],
});
ViewBag.SelectList = Yearitems;
int DateId=0;
string CityName = string.Empty;
try
{
int SelectedYear = Convert.ToInt16(collection["Yearitems"].ToString());
int SelectedMonth = Convert.ToInt16(collection["MonthItems"].ToString());
CityName = collection["CityNames"].ToString();
DateId = _repository.GetImportDateId(SelectedYear, SelectedMonth);
ViewBag.SelectedYear = SelectedYear;
ViewBag.SelectedMonth = SelectedMonth;
ViewBag.SelectedCity = CityName;
}
catch(NullReferenceException Ex)
{
Console.WriteLine(Ex);
}
//IEnumerable<SelectListItem> MonthItems = (from m in SelectMonthList
// select new SelectListItem()
// {
// Value = m.MonthSelectedId.ToString(),
// Text = m.MonthName,
// });
//ViewBag.SelectMonthList = MonthItems;
IEnumerable<SelectListItem> MonthItems = Enumerable.Empty<SelectListItem>();
ViewBag.SelectMonthList = MonthItems;
List<AirtelManagementModel> list = ViewDetails();
ViewBag.CurrentSort = sortorder;
ViewBag.PhoneSortParm = String.IsNullOrEmpty(sortorder) ? "Phone_desc" : "";
if (searchString != null )
{
page = 1;
}
else
{
searchString = currentFilter;
}
//if(searchString!=null)
//{
ViewBag.CurrentFilter = searchString;
var airteldetails = from _model in list
select _model;
if(!String.IsNullOrEmpty(searchString) && DateId!=0 && !String.IsNullOrEmpty(CityName))
{
airteldetails = _repository.FilterAirtelDetails(searchString, DateId, CityName);
int PageSize = 5;
int PageNumber = (page ?? 1);
return View(airteldetails.ToPagedList(PageNumber, PageSize));
}
//airteldetails=airteldetails.OrderByDescending(A=>A.AirtelNumber);
int pageSize = 5;
int pageNumber = (page ?? 1);
//return View(airteldetails.ToList());
return View(airteldetails.ToPagedList(pageNumber, pageSize));
}
View
<h2 style="text-align:center">AirtelDetails</h2>
#using (Html.BeginForm("ViewDataOfDatabase", "AirtelManagement",FormMethod.Post))
{
<h3>Search by PhoneNumber:#Html.TextBox("SearchString",ViewBag.CurrentFilter as string)</h3>
<p><h3>Year:#Html.DropDownList("Yearitems",(IEnumerable<SelectListItem>)ViewBag.SelectList, "Select Year")</h3>
<h3>Month:#Html.DropDownList("MonthItems", (IEnumerable<SelectListItem>)ViewBag.SelectMonthList, "Select Month")</h3>
<h3>City: #Html.DropDownList("CityNames", (IEnumerable<SelectListItem>)ViewBag.CityList, "Select City")</h3></p>
<p><input type="submit" value="Search" /></p>
<script>
$(document).ready(function () {
$("#Yearitems").change(function () {
//debugger;
//alert($("#Yearitems>option:selected").attr("Value"));
$.ajax({
type: "Post",
url: '#Url.Action("GetMonths","AirtelManagement")',
data: { YearId: $("#Yearitems>option:selected").attr("Value") },
datatype: "Json",
success: function (data) {
//debugger;
$("#MonthItems").html("");
$.each(data, function (index, item) {
$("#MonthItems").append(new Option(item.MonthName, item.MonthSelectedId));
});
},
error: function () {
alert("Select Year");
}
});
});
});
</script>
}
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("ViewDataOfDatabase", "AirtelManagement", new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))