I use DataTable in my Django project and currently doing internationalisation of my apps
I would like DataTable change with browser language as for my templates.
I have found the way to change language with DataTable option
var table = $('#table_id').DataTable({
lengthMenu: [5,10],
"language": {
"url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/French.json"
}
});
is their a simple way doing it?
or should I test for browser language and have a switch to initialize var table?
something like that (pseudocode):
if browser.lang == 'english'{
var table = $('#table_id').DataTable({
lengthMenu: [5,10],
});
}
else {
var table = $('#table_id').DataTable({
lengthMenu: [5,10],
"language": {
"url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/French.json"
}
});
}```
Try to make a comparision between:
var lang = navigator.languages && navigator.languages[0] ||
navigator.language || navigator.userLanguage;
Var language is different on current browsers
thanks to Synapsido that show me the way...
below the code I use
<script>
$(document).ready( function () {
if(window.navigator.language == 'fr-FR'){
var table = $('#table_id').DataTable({
lengthMenu: [5,10],
"language": {
"url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/French.json"
}
});
} else {
var table = $('#table_id').DataTable({
lengthMenu: [5,10],
});
}
Related
I'm learning to work with JSON and so I'm running a simple example to create a list item in my template for each object in my django model. My output looks like this:
So I wanted each <li> to show just the actual value in Name. How can I amend my code to achieve that?
views.py
def Ajax(request):
if request.is_ajax():
exporter = serializers.serialize("json", Proforma.objects.all())
print(exporter)
data = json.dumps(exporter)
return HttpResponse(data, content_type='application/json')
$("#populate").click(function() {
$.ajax({
url: "/ajax/more",
success: function(data) {
for(i = 0; i < data.length; i++){
$('ul').append('<li>'+data[i]+'</li>');
}
}
});
});
EDIT:
Here is the output from the console:
(index):739 [{"model": "Poseidon.proforma", "pk": 24, "fields": {"Name": "greg", "Shipment": 4, "Exporter": "greg", "QuoteNo": "jiojo", "Date": "ijoi", "Consignee": 10, "MethodOfDispatch": "ujhiuh", "TypeOfShipment": "iuhiu", "PortOfLoading": "huyg", "PortOfDischarge": "uioj", "Terms": "iugh", "ProductCode": "utyg", "DescriptionOfGoods": "iuhi", "UnitQty": "ug", "UnitType": "t", "Price": "iuh", "Amount": "iy", "BankDetails": "guyt", "AdditionalInfo": "gy", "InvoiceTotal": "tf", "Place": "uyg", "SignatoryCompanyBuyer": "uyf", "SignatoryCompany": "utfy", "NameSignerBuyer": "guyg", "NameSigner": "uy", "SignatureBuyer": "fy", "Signature": "trf", "CreatedBy": "uyg"}}]
the problem is the ajax because you cant print a whole object in the li tag:
try this(would print "Poseidon.proforma" on the li tag):
$("#populate").click(function() {
$.ajax({
url: "/ajax/more",
success: function(data) {
var data = JSON.parse(data); // parse the string response to JSON
for(i = 0; i < data.length; i++){
$('ul').append('<li>'+data[i]["model"]+'</li>');
}
}
});
});
if you want a to understand the problem i think w3schools may help
I'm having trouble getting data from the backend (Python API) to show in react-table manually. I've read the documentation and I'm trying to use the example here: https://react-table.js.org/#/story/server-side-data
I'm only seeing data in one column and only for 6 records which is really weird. It's probably the way I'm mixing in async/await syntax with the example code which uses a promise. I was able to create a simple react-table fetching data with the same async/await syntax, but when I added the server-side data code from the example (the requestData function) it wouldn't work.
I've spent days on this and looking all over Stackoverflow and the internet. I'm a newbie so please go easy on me. Here's what I have:
import React from 'react'
import { render } from 'react-dom'
import ReactTable from 'react-table'
import api from 'src/api'
import { orderBy } from 'lodash'
// importing react-table css would not work so I added it using cdn link
const requestData = async (pageSize, page, sorted, filtered) => {
// api is a wrapper for axios.create()
const rawData = await api.admin.exercise.feed()
return new Promise((resolve, reject) => {
let filteredData = rawData;
if (filtered.length) {
filteredData = filtered.reduce((filteredSoFar, nextFilter) => {
return filteredSoFar.filter(row => {
return (row[nextFilter.id] + "").includes(nextFilter.value);
});
}, filteredData);
}
const sortedData = orderBy(
filteredData,
sorted.map(sort => {
return row => {
if (row[sort.id] === null || row[sort.id] === undefined) {
return -Infinity;
}
return typeof row[sort.id] === "string"
? row[sort.id].toLowerCase()
: row[sort.id];
};
}),
sorted.map(d => (d.desc ? "desc" : "asc"))
);
const res = {
rows: sortedData.slice(pageSize * page, pageSize * page + pageSize),
pages: Math.ceil(filteredData.length / pageSize)
};
resolve(res);
});
};
export class ExerciseList extends React.Component {
constructor() {
super();
this.state = {
data: [],
pages: null,
loading: true
};
this.fetchData = this.fetchData.bind(this);
}
setLoading(loading) {
this.setState({ loading })
}
fetchData(state, instance) {
this.setLoading(true);
requestData(
state.pageSize,
state.page,
state.sorted,
state.filtered
).then(res => {
this.setState({
data: res.rows,
pages: res.pages,
loading: false
});
});
}
render() {
const { data, pages, loading } = this.state;
return (
<div>
<ReactTable
columns={[
{
Header: "Name",
accessor: "name"
},
{
Header: "Movement",
accessor: "movement"
},
{
Header: "Equipment",
accessor: "equipments"
},
{
Header: "Channel",
accessor: "channel"
},
{
Header: "Level",
accessor: "skill_level"
},
{
Header: "Duration",
accessor: "duration",
filterable: false
},
{
Header: "Injuries",
accessor: "injuries"
},
{
Header: "Is Substitute",
accessor: "has_video",
Cell: ({ value }) => (value? 'Yes': 'No'),
filterable: false
}
]}
data={data}
pages={pages}
loading={loading}
onFetchData={this.fetchData}
manual
filterable
defaultPageSize={10}
className="-striped -highlight"
/>
</div>
);
}
}
render(<ExerciseList />, document.getElementById('datatable'));
Please refer the link for server-side sorting, pagination and manual filtering within the grid
// Component related to methods for sorting, pagination server side and filtering manual filtering with in the grid
import React from 'react'
import 'react-table/react-table.css'
import ReactTable from 'react-table'
import autoBind from 'react-autobind'
import {filterCaseInsensitive} from '../../helper/commonMethods'
class ServerSideAtomGrid extends React.Component {
super(props)
const userDetails = getUserDetails()
this.state = {
page: 0,
pageSizeOptions: [500, 1000, 2000, 4000],
pageSize: 500,
totalRecords: 0,
nextCursor: '*',
cursorList: [{
page: 0,
cursor: '*'
}],
sortFields: {
field: 'created_dtm',
sort: 'desc'
},
columnData,
}
autoBind(this)
}
handlePageChange (page) {
const pageNumber = (page)
const cursorList = this.state.cursorList
let cusrsorMark = ''
_.each(cursorList, (list) => {
if (list.page === pageNumber) {
cusrsorMark = list.cursor
}
})
this.setState({
nextCursor: cusrsorMark,
page: pageNumber
}, () => this.searchData(cusrsorMark, pageNumber))
}
handleSizePerPageChange (pageSize) {
this.resetData(pageSize)
this.searchData('*', 0)
}
handleSorting = (state, instance) => {
const sorted = state
let field = 'created_dtm'
let sort = 'desc'
sorted && sorted.length > 0 && sorted.map(fld => {
field = fld.id
sort = fld.desc ? 'desc' : 'asc'
})
this.setState({
sortFields: {
field,
sort
}
}, () => this.searchData('*', 0))
}
////
searchData('*', 0) {
//Axios call you cna have
}
filterCaseInsensitive (filter, row) {
const id = filter.pivotId || filter.id
return row[id] ? row[id].toString().toLowerCase().includes(filter.value.toLowerCase()) : true
}
render () {
const {
classes, gridData, gridColumns, defaultFilter, totalRecords,
gridPageSizeOptions, gridPage, gridPages, gridPageSize, gridLoading
} = this.props
return (
<div>
<ReactTable
columns={gridColumns}
data={gridData}
onSortedChange={(state, instance) => {
this.handleSorting(state, instance)
}}
filterable={defaultFilter}
defaultFilterMethod={filterCaseInsensitive}
noDataText="Ops No result found!"
defaultPageSize={this.state.pageSize}
className="-highlight"
style={{height: `${totalRecords < 25 ? '' : `800px`}`, width: '100%', textAlign: 'center'}}
pageText={`Total Count : ${totalRecords.toLocaleString()} Page: `}
loading={gridLoading}
page={this.state.page}
pages={this.state.pages}
showPaginationTop
pageSize={this.state.pageSize}
pageSizeOptions={gthis.state.pageSizeOptions}
minRows={25}
manual
onPageChange={page => {
this.setState({page})
this.handlePageChange(page)
}}
onPageSizeChange={(pageSize, page) => {
this.setState({
page,
pageSize
})
this.props.handleSizePerPageChange(pageSize)
}}
showPageJump={false}
/>
</div>
)
}
}
export default (ServerSideAtomGrid)
My Fiddle: https://jsfiddle.net/gowthamguruju/o9ybxqaj/8/
A bit of a general question - I am looking for ways to refresh a graph on a Django page based on user choices. The page has a graph, a few drop boxes where you can select parameters and a refresh button. Currently, I can capture the selections via ajax to my Django view and generate new data from database for the graph. I now need to feed that newly-generated data back into the graph and refresh it without a page refresh. Could anyone recommend the best methods of doing this?
Use JQuery to refresh graph without refreshing page.
I am using chart.js to create graph. first create a graph and on change event get updated data using Ajax URL call and assign values to chart data sets.
/** Graph Start Here */
window.chart = null;
$(document).on('change', '.graph-year-earning', function () {
var year = $(this).val();
$.get($('.graph-ajaxload-context').data('href'), { 'year': year, 'number': Math.floor(Math.random() * (1000000 - 10 + 1) + 10) }, function (response) {
window.chart.data.labels = response.labels;
window.chart.data.datasets[0].soldProductLabel = response.product_sold_label;
window.chart.data.datasets[0].totalCommissionLabel = response.monthly_commission_label;
window.chart.data.datasets[0].dataLabel = response.your_share_label;
if (response.total_commission == 0) {
window.chart.options.scales.yAxes[0].ticks.suggestedMin = 0;
window.chart.options.scales.yAxes[0].ticks.suggestedMax = 140000;
} else {
window.chart.options.scales.yAxes[0].ticks.suggestedMin = '';
window.chart.options.scales.yAxes[0].ticks.suggestedMax = '';
}
$.each(response.data, function (index, value) {
window.chart.data.datasets[0].soldProduct[index] = value[2];
window.chart.data.datasets[0].data[index] = Math.round(value[0]);
});
window.chart.update();
$(".txt-total-commission-by-year").html(response.total_commission)
$('.graph-ajaxload-context .inline-loader').hide();
});
});
if ($('.graph-ajaxload-context').length > 0) {
showLoader()
$('.graph-year-earning').trigger('change');
var ctx = $('#userEarningGraph');
window.chart = new Chart(ctx, {
type: 'bar',
data: {
labels: [],
datasets: [{
soldProductLabel: '',
soldProduct: [],
dataLabel: '',
data: [],
backgroundColor: '#ADAEB1',
hoverBackgroundColor: '#48C6B9'
}]
},
options: {
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
maxTicksLimit: 8,
userCallback: function (value, index, values) {
value = value.toString();
value = value.split(/(?=(?:...)*$)/);
value = value.join(',');
var currency_code = ' ₩'
if ($('.graph-ajaxload-context').data('currency-code') && $('.graph-ajaxload-context').data('currency-code') != 'None') {
currency_code = $('.graph-ajaxload-context').data('currency-code')
}
return value + ' ' + currency_code;
}
},
}]
},
tooltips: {
mode: 'label',
callbacks: {
label: function (tooltipItem, data) {
var soldProduct = data.datasets[tooltipItem.datasetIndex].soldProduct[tooltipItem.index];
var soldProductLabel = data.datasets[tooltipItem.datasetIndex].soldProductLabel;
var dataPro = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
var dataLabel = data.datasets[tooltipItem.datasetIndex].dataLabel;
return [soldProductLabel + ':' + soldProduct, dataLabel + ':' + dataPro + ' ₩',];
}
}
}
}
});
}
$(document).on('click', '.showgraph', function (e) {
$('.graph-year-earning').trigger('change');
});
/** Graph End Here */
Being very new to GraphQL, I have a graphene django implementation of a server with two models, following rather closely the graphene docs' example.
In graphiql, I can do this, and get a result back.
Following another relay tutorial, I'm intending to render the result of this query on screen.
My attempt looks like this:
class Note extends Component {
render() {
return(
<div> {this.props.store.title} </div>
)
}
}
Note = Relay.createContainer(Note, {
fragments: {
store: () => Relay.QL`
fragment on Query {
note(id: "Tm90ZU5vZGU6MQ==") {
id
title
}
}
`
}
});
class NoteRoute extends Relay.Route {
static routeName = 'NoteRoute';
static queries = {
store: Component => {
return Relay.QL`
query {
${Component.getFragment('store')}
}
`},
};
}
My browser's console shows the following error:
Uncaught Error: Relay transform error ``There are 0 fields supplied to the query named `Index`, but queries must have exactly one field.`` in file `/Users/.../src/index.js`. Try updating your GraphQL schema if an argument/field/type was recently added.
I've been trying to figure it out on my own with limited success.
Can someone point me in the right direction?
Thanks #stubailo for pointing me in the right direction. I made some adjustments, and now have a minimum example running like this:
NoteList = Relay.createContainer(NoteList, {
fragments: {
store: () => Relay.QL`
fragment N on NoteNodeConnection {
edges {
node{
id
title
note
}
}
}
`
}
});
class NoteRoute extends Relay.Route {
static routeName = 'NoteRoute';
static queries = {
store: Component => {
return Relay.QL`
query {
notes {
${Component.getFragment('store')}
}
}
`},
};
}
I am using django framework and getting some data from local host in json format like this:
[{"stu_name": "Aatir"}, {"stu_name": "Mohsin"}, {"stu_name": "Anil"}, {"stu_name": "Anwar"}, {"stu_name": "Amir"}]
now i want to use this data and want to show in extjs grid
my extjs files are as below:
hmak.html
<html>
<head>
<title>Account Manager</title>
<link rel="stylesheet" type="text/css" href="{{MEDIA_URL}}extjs/resources/css/ext-all.css">
<script type="text/javascript" src="{{MEDIA_URL}}extjs/ext-all-debug.js"></script>
<script type="text/javascript" src="{{MEDIA_URL}}extjs/ext-debug.js"></script>
<script type="text/javascript" src="{{MEDIA_URL}}app.js"></script>
</head>
<body>
</body>
</html>
app.js
Ext.Loader.setConfig({ enabled: true });
Ext.application({
requires : [ 'Ext.container.Viewport'],
controllers: ['Users'],
name: 'AM',
appFolder: 'media/app',
launch: function() {
Ext.create('Ext.container.Viewport', {
layout: 'fit',
items: [
{
xtype: 'userlist'
}
]
});
}
});
Users.js(controller)
Ext.define('AM.controller.Users', {
extend: 'Ext.app.Controller',
stores: ['Users'],
models: ['User'],
views: ['user.List', 'user.Edit'],
init: function() {
this.control({
'viewport > userlist': {
itemdblclick: this.editUser
},
'useredit button[action=save]': {
click: this.updateUser
}
});
},
updateUser: function(button) {
var win = button.up('window'),
form = win.down('form'),
record = form.getRecord(),
values = form.getValues();
record.set(values);
win.close();
this.getUsersStore().sync();
},
editUser: function(grid, record) {
var view = Ext.widget('useredit');
view.down('form').loadRecord(record);
}
});
List.js(view)
Ext.define('AM.view.user.List' ,{
extend: 'Ext.grid.Panel',
alias : 'widget.userlist',
store: 'Users',
title : 'All Users',
initComponent: function() {
this.store = {
fields: ["stu_name"]
};
this.columns = [
{header: "stu_name", dataIndex: "stu_name", flex: 1}
];
this.callParent(arguments);
}
});
Edit.js(view)
Ext.define('AM.view.user.Edit', {
extend: 'Ext.window.Window',
alias : 'widget.useredit',
title : 'Edit User',
layout: 'fit',
autoShow: true,
initComponent: function() {
this.items = [
{
xtype: 'form',
items: [
{
xtype: 'textfield',
name : "stu_name",
fieldLabel: "stu_name"
}
]
}
];
this.buttons = [
{
text: 'Save',
action: 'save'
},
{
text: 'Cancel',
scope: this,
handler: this.close
}
];
this.callParent(arguments);
}
});
Users.js(store)
Ext.define('AM.store.Users', {
extend: 'Ext.data.Store',
model: 'AM.model.User',
autoLoad: true,
proxy: {
type: 'ajax',
api: {
read: 'http://127.0.0.1:8000/task/'
},
reader: {
type: 'json',
root: 'users',
successProperty: 'success'
}
}
});
User.js(model)
Ext.define('AM.model.User', {
extend: 'Ext.data.Model',
fields: ["stu_name"]
});
viewport.js
Ext.define('SI.view.Viewport', {
extend: 'Ext.container.Viewport'
});
and in my python I wrote:
def homePage(request):
StuInfo.objects.all().values_list()
return render_to_response('hmak.html', context_instance=RequestContext(request))
which in turn goes to hmak.html and from localhost/task (which I've define in the proxy) the data which it gets is in the json form as I've show you above json data
Now what is my problem that why my grid is not showing?
it just shows the header...
Can anyone please help me with this problem?
I think You have to change the
Ext.define('SI.view.Viewport', {
extend: 'Ext.container.Viewport'
});
to
Ext.define('AM.view.Viewport', {
extend: 'Ext.container.Viewport'
});
and also deleting the store calling inside of the initComponent function.
This might be the source of your problem:
this.store = {
fields: ["stu_name"]
};
In the initComponent function, you are overwriting the store that you defined in the gridpanel class definition. Have you tried deleting that?