How can I pass the data from Django to a Shield UI Grid? - json

I'm new using Django and Shield UI, what I'm trying to do is trying to get data for a shieldGrid, making a request to get remote data from the server. I have the next code.
this is my .js
$("#id_table_diagnosticos").shieldGrid({
dataSource: {
remote: {
read: {
url: "/atender/ListadoDiagnosticos/",
dataType: "json",
operations: ["sort", "skip", "take"],
data: function (params) {
var odataParams = {};
if (params.sort && params.sort.length) {
odataParams["$orderby"] = window.orderFields[params.sort[0].path].path + (params.sort[0].desc ? " desc" : "");
}
if (params.skip != null) {
odataParams["skip"] = params.skip;
}
if (params.take != null) {
odataParams["top"] = params.take;
}
return odataParams;
}
}
},
schema: {
data: "fields",
total: function (result) {
return result["odata.count"];
},
fields: window.orderFields = {
// "pk": { path: "pk" },
"descripcion": { path: "descripcion" },
"codigo": { path: "codigo" },
}
}
},
paging: true,
sorting: true,
columns: [
// { field: "pk", title: "ID", width: 80 },
{ field: "descripcion", title: "Descripción", width: 180 },
{ field: "codigo", title: "Código", width: 100 },
]
});
});
my model.py is
class ParametrosDiagnosticos(models.Model):
descripcion=models.CharField(max_length=1000)
codigo=models.CharField(max_length=100)
sexo=models.CharField(max_length=10,default='Ambos')
estado=models.CharField(max_length=100, default='Activo')
estado_logico=models.IntegerField(default=1)
and my view.py
def ListadoDiagnosticos(request):
if request.user.is_authenticated:
if request.method=='GET' and request.is_ajax():
objeto=ParametrosDiagnosticos.objects.all()
data = serializers.serialize('json', objeto, fields=('pk','descripcion','codigo'))
return JsonResponse(data,safe=False);
The request to server is doing ok, the problem is that when I return the data, I get the next error on the console of my browser.
shieldui-all.min.js:4 Uncaught TypeError: Cannot read property 'map' of undefined
at e (shieldui-all.min.js:4)
at init.fields (shieldui-all.min.js:5)
at init.process (shieldui-all.min.js:5)
at init._success (shieldui-all.min.js:5)
at e (bundled.js:2)
at Object.z.func.i.success (shieldui-all.min.js:4)
at j (bundled.js:2)
at Object.fireWith [as resolveWith] (bundled.js:2)
at x (bundled.js:5)
at XMLHttpRequest.b (bundled.js:5)
Thank you for your help.

Make sure your Grid's dataSource.schema is configured correctly. Documentation about it can be found here.
For example, if your data returned from the server contains a list of objects, you do not need to set its data property.

Related

ExtJS 6 Rest Proxy where JSON Data Object is ID

I'm hoping someone can guide me on how to deal with this json data structure.
Here's an example of that: (I have zero control of this data)
{
"1": {
"name": "thing 01",
"attributes": {
"color": "red",
"brand": "ACME"
}
},
"2": {
"name": "thing 02",
"attributes": {
"color": "blue",
"brand": "ACME"
}
}
}
So I'm confused about how to get the records using the reader
Ext.define('MyApp.model.Thing', {
extend: 'Ext.data.Model'
fields: [
{ name: 'name' },
{ name: 'attributes', type: 'auto' }
],
proxy: {
type: 'rest',
url: 'http://example.com/api/things',
reader: {
type: 'json',
rootProperty: ??? // <--- How should this work?
}
}
});
I've wondered if there's a way to do something like...
rootProperty: '[id]'
Also is there a way to specify the ID when it is the data object? Maybe somehow using the idProperty config on the Model?
Should I use the reader.format method? That would seem a little gross...
Any ideas are apreciated. Thanks!
Write a custom reader class:
Ext.define('MyReader', {
extend: 'Ext.data.reader.Json',
alias: 'reader.myreader',
config: {
transform: function (data) {
var ret = [],
key, o;
for (key in data) {
o = data[key];
o.id = key;
ret.push(o);
}
return ret;
}
}
});
Ext.define('Thing', {
extend: 'Ext.data.Model',
fields: ['name', 'attribute'],
proxy: {
type: 'ajax',
url: 'data1.json',
reader: {
type: 'myreader'
}
}
});
Example fiddle.
Your EXACT question is already answered here.
You should implement a custom reader and override the getResponseData method.
Ext.define('MyReader', {
extend: 'Ext.data.reader.Json',
alias: 'reader.myreader',
getResponseData: function(response) {
var data = this.callParent([response]);
//do stuff here
return data;
}
});

setting value to deletingStatusText is not working in fineuploader

This a follow up question from.
I am trying to utilize the current Delete process for Caption Update(in my case). The implementation works,but statusText still remains as default (Deleting....). As per the answer in the above link, I tried to set deletingStatusText= 'Updating...' in DeleteFile option. And, I have alert statement in the DeleteFile. Even before displaying the alert, statusText already shows 'Deleting...' please see the screenshot.
It is possible that I am missing something bit I can not figure out what is missing. Do I need set status any other place ?
JS
var isCaptionUpdate = false;
var statusText = "Deleting...";
var captionValue = "";
function captionUpdate(){
isCaptionUpdate = true;
statusText = "Updating...";
};
var manualUploaderSection1 = new qq.s3.FineUploader({
element: document.getElementById('fine-uploader-manual-trigger-section1'),
template: 'qq-template-manual-trigger-section1',
autoUpload: false,
debug: true,
request: {
endpoint: "http://xx_my_bucket_xx.s3.amazonaws.com",
accessKey: "AKIAIAABIA",
},
signature: {
endpoint: "http://localhost/app/ci/php-s3-server/endpoint-cors.php"
},
uploadSuccess: {
endpoint: "http://localhost/app/ci/php-s3-server/endpoint-cors.php?success",
params: {
isBrowserPreviewCapable: qq.supportedFeatures.imagePreviews
}
},
session: {
endpoint: "http://localhost/app/ci/php-s3-server/endpoint-cors.php?filelist"
},
iframeSupport: {
localBlankPagePath: "success.html"
},
cors: {
expected: true
},
chunking: {
enabled: true
},
resume: {
enabled: true
},
deleteFile: {
enabled: true,
method: "POST",
endpoint: "http://localhost/app/ci/php-s3-server/endpoint-cors.php",
deletingStatusText: statusText,
params: {
qqcaption: function(id, name) {
alert(statusText);
if (isCaptionUpdate === true) {
isCaptionUpdate = false;
return captionValue;
}
}
}
},
validation: {
itemLimit: 5,
sizeLimit: 15000000
},
thumbnails: {
placeholders: {
notAvailablePath: "http://localhost/app/ci/s3.fine-uploader/placeholders/not_available-generic.png",
waitingPath: "http://localhost/app/ci/s3.fine-uploader/placeholders/waiting-generic.png"
}
},
callbacks: {
onComplete: function(id, name, response) {
var previewLink = qq(this.getItemByFileId(id)).getByClass('preview-link')[0];
if (response.success) {
previewLink.setAttribute("href", response.tempLink)
}
},
onUpload: function(id, fileName) {
captionValue = qq(this.getItemByFileId(id)).getByClass('qq-edit-caption')[0].value;
this.setParams({'qqcaption':captionValue});
},
onDelete: function(id) {
captionValue = qq(this.getItemByFileId(id)).getByClass('qq-edit-caption')[0].value;
}
}
});
qq(document.getElementById("trigger-upload-section1")).attach("click", function() {
manualUploaderSection1.uploadStoredFiles();
});

No HTTP resource was found that matches the request URI 'http://localhost:xxx:

I am working on .net web api.....
Web Api Config :
public static void Register(HttpConfiguration config)
{
// Verb Routing
RouteTable.Routes.MapHttpRoute(
name: "SmallBizApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new
{
id = RouteParameter.Optional,
action = RouteParameter.Optional
}
);
config.Formatters.Clear();
config.Formatters.Insert(0, new SmallBiz.WebAPI.Common.JsonpFormatter());
}
I am using jsonp format to load data in kendo-ui Gantt chart as can be seen...
<div id="grid"></div>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function () {
var projectdata = "http://localhost:1799/api",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: projectdata + "/project",
dataType: "jsonp"
},
update: {
url: projectdata + "/project/put",
dataType: "jsonp"
},
destroy: {
url: projectdata + "/project/delete",
dataType: "jsonp"
},
create: {
url: projectdata + "/project/post",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProjectId",
fields: {
ProjectId: { editable: false, nullable: false },
Name: { validation: { required: true } },
Status: { validation: { required: true } },
IsActive: { type: "boolean" }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
toolbar: ["create"],
scrollable: false,
sortable: true,
groupable: true,
columns: [
{ field: "Name", title: "Project Name", width: "170px" },
{ field: "Status", title: "Status", width: "110px" },
{ field: "IsActive", title: "Active", width: "50px" },
{ command: ["edit", "delete", "Setting","Task"], title: " ", width: "150px" }
],
editable: "popup"
});
});
</script>
Controller code :
public IQueryable<ProjectsDM> GetProject()
{
return db.Project;
}
[HttpPut]
public IHttpActionResult PutProjectsDM(int id, ProjectsDM projectsdm)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != projectsdm.ProjectId)
{
return BadRequest();
}
db.Entry(projectsdm).State = EntityState.Modified;
try
{
projectsdm.ModifiedBy = "adnan";
projectsdm.ModifiedDate = DateTime.Now;
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!ProjectsDMExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
Get method/action is working fine in kendo grid but i face problem
with put method/action(when we try to edit some record in grid)....
The errors in firebug .net tab
Response : "Message": "No HTTP resource was found that matches the
request URI 'http://localhost:1799/api/project
/put?callback=jQuery191012879030621062526_1433486934717&models=[{\"ProjectId\":2%2C\"ClientId\":1%2C
\"FirmId\":1%2C\"Status\":\"Started\"%2C\"Name\":\"Flexi77\"%2C\"IsActive\":true%2C\"CreatedDate\":\"2015-06-03T00
:00:00\"%2C\"ModifiedDate\":\"2015-06-03T00:00:00\"%2C\"CreatedBy\":\"adnan\"%2C\"ModifiedBy\":\"adnan
\"}]&_=1433486934719'.",
> "MessageDetail": "No action was found on the controller 'Project'
that matches the name 'put'."
json : "No action was found on the controller 'Project' that matches
the name 'put'."
Is there some route error or stupid mistake, please do help....
any kind of hint/help is much appreciated....
thanks for your time
The problem is that your Web API action expects two parameters:
int id, it's missing from the request URL
ProjectsDM projectsdm, can be retrieved from the payload (request body)
You need to use an URL that includes the missing id parameter. In the route template it's optional, but, if it's missing, as the action which requires it, the action cannot be chosen by the action selector.
So either add the id to the URL, or remove the id parameter from the action.

Web API Odata not returning correct metadata

I'm using OData v4 with Web API to communicate with my AngularJS web application.
More specifically I'm trying to display my data using Kendo UI Grid.
My problem is, that my Web API does not return the correct metadata, resulting in Kendos datasource not being able to display the data.
I'm doing paging, and to do that I need the "count" property in my response for Kendo UI Grid datasource to be able work properly.
The response I'm expecting the Web API should look something like this:
http://docs.oasis-open.org/odata/odata-json-format/v4.0/errata02/os/odata-json-format-v4.0-errata02-os-complete.html#_Toc403940644
However, the result I'm seeing in the response is:
{
"#odata.context":"http://localhost:1983/odata/$metadata#TestReports","value":[
{
"Id":1,"Name":"Test Testesen","Purpose":"Kendo UI Grid Test","Type":"Rumraket","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
},{
"Id":2,"Name":"Gunner Testesen","Purpose":"OData Web API Test","Type":"Sutsko","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
},{
"Id":3,"Name":"Bertram Didriksen","Purpose":"Server Paging Test","Type":"Flyver","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
},{
"Id":4,"Name":"Oluf Petersen","Purpose":"Test","Type":"B\u00e5d","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
},{
"Id":5,"Name":"Alfred Butler","Purpose":"Opvartning","Type":"Batmobil","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
}
]
}
My code for retrieving the data is:
$scope.pendingReports = {
dataSource: {
type: "odata",
transport: {
read: {
beforeSend: function (req) {
req.setRequestHeader('Accept', 'application/json;odata=fullmetadata');
},
url: "/odata/TestReports",
dataType: "odata"
},
parameterMap: function (options, type) {
var paramMap = kendo.data.transports.odata.parameterMap(options);
console.log(paramMap);
delete paramMap.$inlinecount; // <-- remove inlinecount parameter
delete paramMap.$format; // <-- remove format parameter
console.log(paramMap);
return paramMap;
}
},
schema: {
data: function (data) {
return data; // <-- The result is just the data, it doesn't need to be unpacked.
},
total: function (data) {
return data.length; // <-- The total items count is the data length, there is no .Count to unpack.
}
},
pageSize: 5,
serverPaging: true,
serverSorting: true
},
sortable: true,
pageable: true,
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
columns: [
{
field: "Name",
title: "Navn"
}, {
field: "ReportedDate",
title: "Indberetet den"
}, {
field: "Purpose",
title: "Formål"
}, {
field: "Type",
title: "Type"
}, {
field: "options",
title: "Muligheder"
}
]
};
My WebApiConfig class is corrently like this:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Formatters.InsertRange(0, ODataMediaTypeFormatters.Create());
config.MapODataServiceRoute(
routeName: "odata",
routePrefix: "odata",
model: GetModel()
);
}
public static Microsoft.OData.Edm.IEdmModel GetModel()
{
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<TestReport>("TestReports");
return builder.GetEdmModel();
}
}
Does anyone have any suggestions on how I get the Web API to return the correct metadata?
Apparently Kendo UI Grid is not supporting OData v4.
The fix was to modify the parameterMap of the Kendo datasource, and tell it to use $count instead of $inlinecount.
Besides that I had to tell the schema to read "#odata.count" as the "total" value.
After I edited the before posted code to the ode below, I got the correct data in my response:
$scope.pendingReports = {
dataSource: {
type: "odata",
transport: {
read: {
beforeSend: function (req) {
req.setRequestHeader('Accept', 'application/json;odata=fullmetadata');
},
url: "/odata/TestReports",
dataType: "json"
},
parameterMap: function (options, type) {
var d = kendo.data.transports.odata.parameterMap(options);
delete d.$inlinecount; // <-- remove inlinecount parameter
d.$count = true;
return d;
}
},
schema: {
data: function (data) {
return data.value; // <-- The result is just the data, it doesn't need to be unpacked.
},
total: function (data) {
return data['#odata.count']; // <-- The total items count is the data length, there is no .Count to unpack.
}
},
pageSize: 5,
serverPaging: true,
serverSorting: true
},
sortable: true,
pageable: true,
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
columns: [
{
field: "Name",
title: "Navn"
}, {
field: "ReportedDate",
title: "Indberetet den"
}, {
field: "Purpose",
title: "Formål"
}, {
field: "Type",
title: "Type"
}, {
field: "options",
title: "Muligheder"
}
]
};

Sencha touch2: How can i parse my nested json data?

i could not able to parse my nested json data and i tried in many ways but i could not succeed. any help is appreciated.
Here is my json output looks like:
[
{
"task": {
"locator": "FGWESD",
"subtask": [
{
"work": {
"number": "1145",
"id": "0",
"status": true,
"gate": "N\/A",
},
"sequenceNumber": "0",
"id": "0"
},
{
"work": {
"number": "1145",
"id": "0",
"status": true,
"gate": "N\/A",
},
"sequenceNumber": "0",
"id": "0"
}
],
"connectTime": "0",
"id": "0"
}
}
]
Here is my model:
Ext.define('MyApp.model.MyModel',{
extend:'Ext.data.Model',
xtype:'myModel',
config:{
fields:[
{name:'number',mapping:'work.number'},
{name:'id',mapping:'work.id'},
{name:'locator',mapping:'task.locator'},
{name:'gate',mapping:'work.gate'}
]
}
});
Here is the store:
Ext.define('MyApp.store.StoreList', {
extend:'Ext.data.Store',
config:{
model:'MyApp.model.MyModel',
storeId: 'id_Store',
// added the url dynamically inside the controller
proxy:{
type:'ajax',
reader:
{
type:"json",
rootProperty: 'subtask'
},
method: 'POST',
actionMethods: {
create : 'POST',
read : 'POST', // by default GET
update : 'POST',
destroy: 'POST'
},
headers :{
"Content-Type" :'application/xml',
'Accept':'application/json'
}
}
}
});
Here is my controller code :
Ext.define('MyApp.controller.LoginController', {
extend: 'Ext.app.Controller',
requires: ['Ext.data.proxy.Rest'],
config: {
// My code is too long to add here so am adding store loading when user taps login button
},
getDetails: function(){
var segmentStore = Ext.create('MyApp.store.StoreList');
var url = 'http://localhost:8080/apps';
segmentStore.getProxy().setUrl(url.trim());
segmentStore.load({
scope:this,
callback: function(records, operation, success){
if(success){
console.log('records: ',records);
console.log('records: '+records.length); // prints here 1
console.log('locator: '+records[0].getData().locator);
// prints FGWESD
console.log('locator: '+records[0].getData().number);
//prints undefined
//
}
}
}
)
},
});
Can any one please help me out. how can i get Values of number, gate, id and status?
What are the necessary changes have to be made in model, store and controller ?
Please help me out in resolving ? Thanks.
As I wrote in a comment, I don't think you can achieve that without manually parsing the data and loading it to the store. So the getDetails function should look like this:
getDetails: function(){
var segmentStore = Ext.create('MyApp.store.StoreList');
Ext.Ajax.request({
url: 'http://localhost:8080/apps',
success: function(response){
var responseObj = Ext.decode(response.responseText);
var task = responseObj[0].task;
var locator = task.locator;
var subtasks = [];
Ext.each(task.subtask, function(subtask) {
subtasks.push({
number: subtask.work.number,
id: subtask.work.id,
gate: subtask.work.gate,
locator: locator
});
});
segmentStore.setData(subtasks);
}
});
}
Also, when using this method you should remove the mapping from your model, and you can get rid of the proxy definition of the store. Also, I'm not sure why you want to create the store in the "getDetails" and not define it in the 'stores' config of the controller, but maybe you have your reasons..
I didn't run the code, so there maybe errors, but I hope you get the idea.
I think the root property of your store should be:
rootProperty: 'task.subtask'