I need to write a compatible algorithm for this code, but I can't. How can I send data to backend?
I am using bootstable.js for table
HTML table:
<table class="table table-bordered" id="table-list">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Slug</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{% for chart in charts %}
<tr>
<th id="id">{{chart.id}}</th>
<td class="editable" id="name">{{chart.name}}</td>
<td class="editable" id="slug">{{chart.slug}}</td>
<td>john#example.com</td>
</tr>
{% empty %}
<p>No data</p>
{% endfor %}
</tbody>
</table>
And this is my JavaScript code. I tried to try some methods myself but it didn't work
<script src="{% static 'npe_cp/js/bootstable.js' %}"></script>
<script>
//apply
$("#table-list").SetEditable();
$('#addRow').click(function() {
rowAddNew('table-list');
});
$('#bAcep').on('click', function(){
// var id=$("#id").val();
// var name=$("#name-44").val();
// var slug=$("#slug-44").val();
let name=document.querySelector('#name')
console.log(id, name, slug, 'Hello World')
$.ajax({
url:"/chart/edit",
type:"POST",
data:{
"id":id,
"name":name,
"slug":slug,
},
})
});
This is exactly what the table looks like. I want to update, create, and delete operations. But I am not getting the data.
Use Django Forms to populate the database, makes it easy to perform CRUD operations
Related
I've a separate javascript code which is fetching data from api and inserting in browsers localStorage.
API is fetching ETA data and saving in localStorage as id_ETA(e.g 12342_ETA) key.
When the values in local storage gets updated then my html table ETA column values should also get updated without refreshing the page.
Right now I need to refresh the entire page in order to view the updated ETA in the html.
HTML Table:
<div class="container">
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Arrival Address</th>
<th>Departure Address</th>
<th>ETA</th>
</tr>
</thead>
<tbody>
<script>
var data = getPlanData();
<div class="container">
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Arrival Address</th>
<th>Departure Address</th>
<th>ETA</th>
</tr>
</thead>
<tbody>
for(var i=0;i<data.length;i++){
document.write("<tr>");
document.write("<td>"+data[i]['id']+"</td>");
document.write("<td>"+data[i]['arrival']+"</td>");
document.write("<td>"+data[i]['departure']+"</td>");
document.write("<td>"+data[i]['arrival']+"</td>");
if (localStorage.getItem(data[i]['id']+'_ETA'))
{
document.write("<td>"+localStorage.getItem(data[i]['id']+'_ETA')+"</td>");
}
else
{
document.write("<td>-</td>");
}
document.write("</tr>");
</script>
</tbody>
</table>
</div>
getPlanData():
function getPlanData() {
localData = localStorage.getItem('plan');
result = csvToJSON(localData);
return result;
}
Note: ETA is coming from separate API
Is there a way to update the ETA column when there is new ETA value in localStorage without refreshing the page?
Assuming getPlanData() does the writing to localStorage, you need to do two things
Don't use document.write, certainly not after load since it wipes the page
save to localStorage in getPlanData() AND
call this update with the data in the getPlanData function - this script can be copied to the head of the document inside script tags and called as update(data)
const update = data => {
const html = data.map(item => (
`<tr>
<td>${item.id}</td>
<td>${item.arrival}</td>
<td>${item.departure}</td>
<td>${item.arrival}</td>
<td>${localStorage.getItem(item.id+"_ETA") || "-"}</td>
</tr>`));
document.querySelector(".table tbody").innerHTML=html.join("")
}
<div class="container">
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Arrival Address</th>
<th>Departure Address</th>
<th>ETA</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
If you post an example of your data, I am sure we can find a better way to get the ETA than localStorage.getItem(item.id+"_ETA")
UPDATE: You CAN do
var data = getPlanData();
update(data)
I have flask sending data to html. Now, first time it does that its by render_template('page1.html', data=data) which populates the main table. Now when i click on any row of main table, i want to call flask again by url_for(entrypoint) and then again i will do render_template('page1.html', data=data2) for the 2nd table. But how to differentiate between them? i mean how will html know which data is coming for whom? please advice. I am novice in javascript and html. I am planning to keep the main table and secondary table under different forms. please advice if thats good decision or not.
Inside my html(page1.html), I have written
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
function getId(element) {
var row_index=element.rowIndex;
$.ajax({
url: '/get_details',
data: document.getElementById("table1").rows[row_index].cells[5].innerHTML),
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
This is the code in html for table1 and table2(table2 not done yet)
<section id="boxes" style="margin-top:-5%; margin-bottom:0%; position:absolute; z-index:1;">
<div class="box" style="margin-left:30px; margin-top:20px; z-index:1;">
<table id="table1">
<tr>
<th>NO</th>
<th> SUBJECT NAME</th>
<th>ASSIGNED TO</th>
<th>CREATED</th>
<th>DISEASES</th>
<th>SUBJECT ID</th>
<th>STATUS</th>
</tr>
{% for row in data %}
<tr onclick="getId(this)">
<td> {{ row[0] }}</td>
<td> {{ row[1] }}</td>
<td> {{ row[2] }}</td>
<td> {{ row[3] }}</td>
<td> {{ row[4] }}</td>
<td> {{ row[5] }}</td>
<td> {{ row[6] }}</td>
</tr>
{% endfor %}
</table>
</div>
<div class="box-two">
</div>
Inside my app.py
here is the flask code for the entry point:
#app.route('/get_details', methods=['POST'])
def get_details_user(patientid):
print(patientid)
This is the code for the entrypoint for the records which populates table1 as of now:
#app.route('/records')
#login_required
def records():
if current_user.priviledge:
data = get_records_by_userid(None)
else:
data = get_records_by_userid(current_user.id)
list_data = []
for row in data:
list_data.append([])
for col, val in row.items():
list_data[-1].append(val)
return render_template('records.html', data=list_data)
I don't see this in my flask code being triggered. Something wrong in my ajax code?? Also, how do I get the data from flask to this same html file for the second table?
Thanks a lot,
Sudip
Update: The error was coming due to ajax function syntax. Went with extra ')' in data in ajax...oops, thats bad
Add this to the JAvascript code:
$.ajax(function() {
headers = {'X-CSRFToken' : $('#csrf_token').val() },
...
});
This is the token the allows AJac to be validated
I want to print table row information in a Javascript function bind to the onclick event of a button.
view.py
def table(request):
test_list = TestInformation.objects.order_by()
context = { 'test_list' : test_list, }
return render(request, '/test.html', context)
test.html
<label ~~ id="btn_click" onclick="btn()">
<table class="table table-bordered" id="data_table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
{% for li in test_list %}
<tr>
<td> {{ li.Id }} </td>
<td> {{ li.Name}} </td>
</tr>
{% endfor %}
</tbody>
</table>
<Script type="text/javascript">
function btn {
//I'd like to put above {for~~ endfor} source here!
}
</Script>
Currently Action
The table is displayed as soon as you load the html page.
Expected Action
Only visible when the table presses a button
How can I invoke Python objects in JavaScript functions for the actions I expect?
I've been looking for the way to solve this problem but I couldn't find any.
I have a list of scheduled tasks, I get some data from each one, doing an AJAX call and display it throught handlebars:
function getScheduledTasks(URL_address){
$.ajax({
url: URL_address,
success: function(data){
var source = $("#scheduled-task").html();
var template = Handlebars.compile(source);
$('.scheduledBody').append(template(data));
},
error: function(data) {
console.log('error', data);
}
});
}
HTML:
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">Name</th>
<th scope="col">Type</th>
<th scope="col">Next Execution</th>
</tr>
</thead>
<tbody class= "scheduledBody">
<script id="scheduled-task" type="text/x-handlebars-template">
{{#each schedules}}
<tr>
<th>{{name}}</th>
<td>{{type}}</td>
<td data-countdown="{{timeSs}}"></td>
</tr>
{{/each}}
</script>
</tbody>
</table>
The thing is, I have the time in milliseconds in timeSs, I would like to process it with some javascript function and get the countdown working in the same "script tag".
I've seen that exist some jquery function that makes this easy, but I have the library blocked in my work network.
I would appreciate any help.
Thanks.
I am newbie to django. I am using jquery datatable plugins in my django application. These datatables are working fine for the small datasets sent from my view. I have a django model which is having 65k records with 5 columns. when I am trying to show these records in jquery datatables the rendered page becoming unresponsive for a moment and the page is loading correctly. Also sorting, searching, pagination features are working fine with reasonable to amount of time. I want to see the page responsive even when I am showing 65k entries in datatables. Is there any way to do this? or what will be the best solution to handle large datasets? Pls suggest me
I came to know that this is because I am trying to format datatables on client side after loading 65k records from the server. Also I googled n knew that server side processing will be the best way to handle this. Any one pls suggest me how to do server side processing in django.
Now, my code is as follows:
part of Inventory.html:
<div class="box-body table-responsive" id='postinfo'>
</div>
InventoryOutputAlldata.html:
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
$(function(){
$('#example1').dataTable({
});
});
</script>
</head>
<table id="example1" class="table table-bordered table-hover">
<thead>
<tr>
<th>Device</th>
<th>Device Type</th>
<th>Mac Address</th>
<th>IP Address</th>
<th>Status</th>
</tr>
</thead>
<tbody >
<form name="trform" method="post">
{% for key,value in data.items %}
<tr class="trselected" onclick="trclick(this)">
<td>{{ value.0 }}</td>
<td>{{ value.1 }}</td>
<td>{{ value.2 }}</td>
<td>{{ value.3 }}</td>
<td>{{ value.4 }}</td>
</tr>
{% endfor %}
</form>
</tbody>
<tfoot>
<tr>
<th>Device</th>
<th>Device Type</th>
<th>Mac Address</th>
<th>IP Address</th>
<th>Status</th>
</tr>
</tfoot>
</table>
</html>
JS:
$(function(){
var data = new Object();
data['showdata'] = 'all';
data["csrfmiddlewaretoken"] = $("input[name='csrfmiddlewaretoken']").val();
$( "#postinfo" ).load( "/alldata/", data, function( response, status, xhr )
{
});
});
URLs.py:
urlpatterns = patterns('',
url(r'^inventory/$', TemplateView.as_view(template_name='inventory.html')),
url(r'^alldata/$', 'NetworkInventory.nmap_integration.alldata'),
)
views.py:
def alldata(request):
postedInfo = request.POST
count = 0
dataDict = {}
dbData = nmap.objects.all()
if 'showdata' in postedInfo and postedInfo['showdata'] == 'all':
for data in dbData:
count += 1
dataDict[count] = []
dataDict[count].append(data.device)
dataDict[count].append(data.devicetype)
dataDict[count].append(data.macaddress)
dataDict[count].append(data.ipaddress)
dataDict[count].append(data.status)
else:
return HttpResponse('Improper Behaviour')
return render_to_response('inventoryOutputAlldata.html',{'data': dataDict})
Please suggest me how can i modify this to work with large datasets.
When you do it that way all of the records are loaded into cache. You need to use iterate.
Perhaps this is what you want.
car_set = Car.objects.all()
for car in car_set.iterator():
#Do something
Or more advanced
djangosnippets
Try this
import gc
def queryset_iterator(queryset, chunksize=1000):
'''''
Iterate over a Django Queryset ordered by the primary key
This method loads a maximum of chunksize (default: 1000) rows in it's
memory at the same time while django normally would load all rows in it's
memory. Using the iterator() method only causes it to not preload all the
classes.
Note that the implementation of the iterator does not support ordered query sets.
'''
pk = 0
last_pk = queryset.order_by('-pk')[0].pk
queryset = queryset.order_by('pk')
while pk < last_pk:
for row in queryset.filter(pk__gt=pk)[:chunksize]:
pk = row.pk
yield row
gc.collect()
You can simply use a page loader for this. You can set the page loader to the time taken for your datatable rendered correctly into the page.