DataTables - Map Data and correcting table layout - ajax

I am integrating the DataTables in Django 2.1. But the table is broken and I can not map the data sent by the server to JS.
This is my configuration JS:
<!-- Bootstrap CSS Section -->
<link href="{% static 'bootstrap/dist/css/bootstrap.min.css' %}" type="text/css" rel="stylesheet">
<link href="{% static 'datatables.net-bs4/css/dataTables.bootstrap4.min.css' %}" type="text/css" rel="stylesheet">
<!-- Bootstrap core JavaScript-->
<script src="{% static 'jquery/dist/jquery.min.js' %}"></script>
<script src="{% static 'bootstrap/dist/js/bootstrap.min.js' %}"></script>
<!-- Datatables plugin JavaScript-->
<script src="{% static 'datatables.net/js/jquery.dataTables.js' %}"></script>
<script src="{% static 'datatables.net-bs4/js/dataTables.bootstrap4.js' %}"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#user-datatable').DataTable({
language: {
"sEmptyTable": "Nenhum registro encontrado",
"sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
"sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
"sInfoFiltered": "(Filtrados de _MAX_ registros)",
"sInfoPostFix": "",
"sInfoThousands": ".",
"sLengthMenu": "_MENU_ Resultados por página",
"sLoadingRecords": "Carregando...",
"sProcessing": "Processando...",
"sZeroRecords": "Nenhum registro encontrado",
"sSearch": "Pesquisar",
"oPaginate": {
"sNext": "Próximo",
"sPrevious": "Anterior",
"sFirst": "Primeiro",
"sLast": "Último"
},
"oAria": {
"sSortAscending": ": Ordenar colunas de forma ascendente",
"sSortDescending": ": Ordenar colunas de forma descendente"
}
},
"processing": true,
"serverSide": true,
"ajax": {
"url": "{% url 'authentication:get_users' %}",
"type": "GET",
"dataSrc": ""
},
"columns": [
{"data": 'name'},
{"data": "email"},
{"data": "last_login"},
{"data": "is_active"},
]
});
});
</script>
My Views.py code:
#login_required
def get_users(request):
object_list = CustomUser.objects.all()
data = serializers.serialize('json', object_list)
return JsonResponse(data, safe=False)
This is the Json generated by Views.py that I can see in Firefox:
[
{
"model": "authentication.customuser",
"pk": 1,
"fields":
{"password": "1234",
"last_login": "2018-09-03T15:17:29.007Z",
"is_superuser": true,
"name": "John",
"username": "john",
"email": "john#mail.com",
"is_staff": true,
"is_active": true,
"groups": [],
"user_permissions": []}
},
{
"model": "authentication.customuser",
"pk": 2,
"fields":
{"password": "12345",
"is_superuser": false,
"name": "Ana",
"username": "ana",
"email": "ana#mail.com",
"is_staff": false,
"is_active": true,
"groups": [],
"user_permissions": []}
},
}
]
How do I map this data in JS DataTable to display correctly in columns?

Besides you have a closing curly brace too many (assume it is a copy paste error) you do not need any mapping or change to the JSON. It is nicely sectioned in an array of fields. The only concern is last_login which seem to be left out occasionally, defaultContent solves that :
columns: [
{ data: 'fields.name'},
{ data: 'fields.email'},
{ data: 'fields.last_login', defaultContent: ''},
{ data: 'fields.is_active'}
]
Set "serverSide": false, your script does not support serverside processing anyway. If you must have serverside processing https://github.com/izimobil/django-rest-framework-datatables seems to support at least django 2.0.

I use the dashboard theme css that I downloaded to use in the application and it has bootstrap4 css for datatables. For some reason it was not rendering correctly. I removed the import of these css and added those from the DataTables site:
Removing:
<link href="{% static 'datatables.net-bs4/css/dataTables.bootstrap4.min.css' %}" type="text/css" rel="stylesheet">
Adding:
<link href="{% static 'datatables/media/css/jquery.dataTables.min.css' %}" type="text/css" rel="stylesheet">
The table is now rendered correctly.

Related

Amcharts put into html

It is very strange that last time I run the program everything is ok, but this time it does not work, the result web page a empty and I really don't know where make the error.(Sorry only add some words to Thank you Thank you Thank you)
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>My first stock chart</title>
<link rel="stylesheet" href="amcharts/style.css" type="text/css">
<style>
#chartdiv
{
width : 100%;
height : 500px;
font-size : 11px;
}
</style>
<script src="https://www.amcharts.com/lib/3/amcharts.js"></script>
<script src="https://www.amcharts.com/lib/3/serial.js"></script>
<script src="https://www.amcharts.com/lib/3/themes/light.js"></script>
<script src="https://www.amcharts.com/lib/3/plugins/dataloader/dataloader.min.js"></script>
<script type="text/javascript">
AmCharts.loadFile("https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-160/22300.csv", {}, function (response) {
/**
* Parse CSV
*/
var data = AmCharts.parseCSV(response, {
"useColumnNames": true
});
/**
* Create the chart
*/
var chart = AmCharts.makeChart("chartdiv", {
"type": "serial",
"theme": "light",
"dataProvider": data,
"valueAxes": [{
"gridColor": "#FFFFFF",
"gridAlpha": 0.2,
"dashLength": 0
}],
"gridAboveGraphs": true,
"startDuration": 1,
"graphs": [{
"balloonText": "[[category]]: <b>[[value]]</b>",
"fillAlphas": 0.8,
"lineAlpha": 0.2,
"type": "column",
"valueField": "visits"
}],
"chartCursor": {
"categoryBalloonEnabled": false,
"cursorAlpha": 0,
"zoomable": false
},
"categoryField": "country",
"categoryAxis": {
"gridPosition": "start",
"gridAlpha": 0,
"tickPosition": "start",
"tickLength": 20
}
});
});
</script>
</head>
<body>
<div id="chartdiv"></div>
</body>
</html>
The CSV file is probably cached now in your browser, this causes Amcharts to immediately create the Chart. Unfortunately the div container doesn't exist yet. Either move your chart initialisation script tag below the chart div or wrap it in a DOMContentLoaded eventlistener or move the script to a separate file.
Option 1 move the script tag below the target div
<body>
<div id="chartdiv"></div>
<script type="text/javascript">
AmCharts.loadFile("https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-160/22300.csv", {}, function (response) {
/**
* Parse CSV ....
*/
});
</script>
</body>
Option 2 wrap initialisation around DOMContentLoaded
document.addEventListener("DOMContentLoaded", function(event) {
AmCharts.loadFile("https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-160/22300.csv", {}, function (response) {
/**
* Parse CSV ....
*/
});
});

how to make kendo treeList cell as hyperlink?

I have an example kendo treeList created: http://dojo.telerik.com/akAwe/4
In the example, how do i make child cells of "Protocol names" column clickable?
Thanks.
Please try with the below code snippet.
<!DOCTYPE html>
<html>
<head>
<base href="http://demos.telerik.com/kendo-ui/treelist/local-data-binding">
<style>
html {
font-size: 14px;
font-family: Arial, Helvetica, sans-serif;
}
</style>
<title>Jayesh Goyani</title>
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2015.2.902/styles/kendo.common-bootstrap.min.css" />
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2015.2.902/styles/kendo.bootstrap.min.css" />
<script src="//kendo.cdn.telerik.com/2015.2.902/js/jquery.min.js"></script>
<script src="//kendo.cdn.telerik.com/2015.2.902/js/kendo.all.min.js"></script>
</head>
<body>
<div id="example">
<div id="treelist"></div>
<script type="text/x-kendo-template" id="template">
<a href='https://www.google.com/?test=#: ProtocolName #'>#: ProtocolName #</a>
</script>
<script>
$(document).ready(function () {
var dataSource = new kendo.data.TreeListDataSource({
data: [
{ "id": 61, "parentId": 1, "ProtocolName": "P2", "SeriesDescription": "P2 " },
{ "ExamStart": "9/19/2015 8:00 AM", "id": 1, "ProtocolName": "P2", "SeriesDescription": "P2 ", "parentId": null },
{ "id": 62, "parentId": 2, "ProtocolName": "P1", "SeriesDescription": "P1 " },
{ "id": 63, "parentId": 2, "ProtocolName": "P2", "SeriesDescription": "P2 ", },
{ "ExamStart": "9/19/2015 8:13 AM", "id": 2, "ProtocolName": "P1, P2", "SeriesDescription": "P1 , P2 ", "parentId": null }
],
schema: {
model: {
id: "id",
expanded: true
}
}
});
$("#treelist").kendoTreeList({
dataSource: dataSource,
height: 540,
columnMenu: true,
dataBound: onDataBound,
columns: [{
field: 'ExamStart',
title: 'Date/Time'
}, {
field: 'ProtocolName',
title: 'Protocol names',
sortable: false,
template: $("#template").html()
}, {
field: 'SeriesDescription',
title: 'Series descriptions',
sortable: false
}]
});
});
function onDataBound(arg) {
$(".k-treelist-group").each(function (index) {
$(this).find('a').replaceWith($(this).find('a').text());
});
}
</script>
</div>
</body>
</html>
Update 1:
<script type="text/x-kendo-template" id="template">
<a href='localhost:20327/\\#/dose/test'>#: ProtocolName #</a>
</script>
Let me know if any concern.

How to change color of row depending on a row's value in a Kendo UI Grid

I have a Kendo UI Grid, which contains four columns:
Highlight MAC Time Message
The Highlight column can contain the values "yes" or "no", and this column is hidden.
I need to create a row template that will highlight (change the color or something) the row if the value is yes.
Please try with the below code snippet.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled</title>
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.common.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.rtl.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.default.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.dataviz.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.dataviz.default.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.mobile.all.min.css">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://cdn.kendostatic.com/2015.1.318/js/kendo.all.min.js"></script>
<style>
.change-background {
background-color: red;
}
</style>
</head>
<body>
<div id="grid"></div>
<script type="text/javascript">
var ds = new kendo.data.DataSource({
data: [{
Highlight: "Yes",
MAC: "111",
Time: "aaa",
Message: "a1"
}, {
Highlight: "No",
MAC: "222",
Time: "bbb",
Message: "b2"
}]
});
$("#grid").kendoGrid({
dataSource: ds,
dataBound: onDataBound,
columns: [
{ hidden: true, field: "Highlight" },
{ field: "MAC" },
{ field: "Time" },
{ field: "Message" }
],
});
function onDataBound(e) {
var grid = $("#grid").data("kendoGrid");
var data = grid.dataSource.data();
$.each(data, function (i, row) {
if (row.Highlight == "Yes") {
var element = $('tr[data-uid="' + row.uid + '"] ');
$(element).addClass("change-background");
}
});
}
</script>
</body>
</html>
Let me know if any concern.
You can apply condition in Row Template, Try Something like below
$("#grid").kendoGrid({
dataSource: ds,
rowTemplate: '<tr class="#:Highlight ==\"Yes\"? \"red\" : \"white\"#" data-uid="#= uid #"><td>#: MAC #</td><td>#:Time #</td><td>#:Message#</td></tr>'
});
DataSource
var ds = new kendo.data.DataSource({
data: [{
Highlight : "Yes",
MAC :"...",
Time :"...",
Message:"...."
}, {
Highlight : "No",
MAC :"...",
Time :"...",
Message:"...."
}]
});

Bind Json result to Grid of kendoUI using ODATA

I want to bind Json result to kendoUI grid using ODATA v4 but i am unable to do so. Below code works for the url http://services.odata.org/v2/Northwind/Northwind.svc/Customers which returns a xml result but why dont it work for http://services.odata.org/v4/Northwind/Northwind.svc/Customers which returns a json. Any help would be appreciated.
<!DOCTYPE html>
<html>
<head>
<base href="http://demos.telerik.com/kendo-ui/grid/index">
<style>html { font-size: 12px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.408/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.408/styles/kendo.material.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.408/styles/kendo.dataviz.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.408/styles/kendo.dataviz.material.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://cdn.kendostatic.com/2015.1.408/js/kendo.all.min.js"></script>
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.408/styles/kendo.common.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.408/styles/kendo.rtl.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.408/styles/kendo.default.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.408/styles/kendo.dataviz.default.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.408/styles/kendo.mobile.all.min.css">
<script src="http://cdn.kendostatic.com/2015.1.408/js/angular.min.js"></script>
<script src="http://cdn.kendostatic.com/2015.1.408/js/jszip.min.js"></script>
</head>
<body>
<div id="example">
<div id="grid"></div>
<script>
$(document).ready(function () {
$("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "http://services.odata.org/v2/Northwind/Northwind.svc/Customers",dataType: "jsonp",data: { q: "#kendoui" }
},
pageSize: 20
},
height: 550,
groupable: true,
sortable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
columns: [{
field: "ContactName",
title: "Contact Name",
width: 200
}, {
field: "ContactTitle",
title: "Contact Title"
}, {
field: "CompanyName",
title: "Company Name"
}, {
field: "Country",
width: 150
}]
});
});
</script>
</div>
</body>
</html>
Couple of things. I don't think the v4 implementation on services.odata.org supports jsonp. The return value doesn't appear to be wrapped. Also you need to change your type to "odata-v4" for v4 odata.
Also the return array isn't inside a property on the return object called "results", it's now "value" so I had to set that in the schema on the dataSource. I also changed the transport.read into an object and added the requisite properties.
dataSource: {
type: "odata-v4",
transport: {
read: {
url: "http://services.odata.org/v4/Northwind/Northwind.svc/Customers",
dataType: "json",
data: {
q: "#kendoui"
}
}
},
pageSize: 20,
schema: {
data: "value"
}
},
See working sample at http://jsbin.com/satafa/1/edit?html,js,output
You need to add "odata-v4" as type in the datasource. Please refer the fiddle
$(document).ready(function () {
$("#grid").kendoGrid({
dataSource: {
type: "odata-v4",
transport: {
read: "http://services.odata.org/v4/Northwind/Northwind.svc/Customers",dataType: "jsonp",data: { q: "#kendoui" }

jqGrid load in MVC

I'm new in jqgrid. I try to use jqgrid in my mvc project. I'm using the following code for mapping the data to grid. But its not working. The function GetJqGridData is loading first in my MVC project.
Below is code for Controler.
public ActionResult GetJqGridData()
{
var jqGridData = new JqGridObject()
{
Data = GetSomeSampleData(),
Page = "1",
PageSize = 3, // u can change this !
SortColumn = "1",
SortOrder = "asc"
};
return Json(jqGridData, JsonRequestBehavior.AllowGet);
}
Below is code for VIEW.
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
<link href="../../Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" type="text/css" />
<link href="../../Content/themes/base/jquery.ui.all.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#myGrid").jqGrid({
url: '#Url.Action("GetJqGridData")',
datatype: 'json',
myType: 'POST',
colNames: ['Id', 'Name'],
colModel: [
{ name: 'Id', index: 'Id' },
{ name: 'Name', index: 'Name' }
],
jsonReader: {
root: 'Data',
id: 'id',
repeatitems: false
},
pager: $('#myPager'),
rowNum: 5,
rowList: [2, 5, 10],
width: 600,
viewrecords: true,
caption: 'Jqgrid MVC Tutorial'
});
});
</script>
<table id="myGrid"></table>
<div id="myPager"></div>
This is result i'm getting
Thanks
Bobbin
Try using the following json format:
{
"total": "xxx",
"page": "yyy",
"records": "zzz",
"rows" : [
{"id" :"1", "cell" :["cell11", "cell12", "cell13"]},
{"id" :"2", "cell":["cell21", "cell22", "cell23"]},
...
]
}
for more informations about the format, take a look in this link : http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data

Resources