Load data on scroll down in Django - javascript

I am currently working on a web application to feature the interface in django and how the content loads.
In my database, potentially thousands of these entries, and I want to make sure that only has to load a given number at a time to reduce stress on the servers etc.
lets say I have 5000 records and initially Load a given number of objects.
then load the next set of records once the I reaches the record at the bottom of the screen.
views.html:
def list(request):
list_data = Container.objects.all()
return render(request,
'list.html',
{'list_data': list_data,})
list.html:
{
% block content %}
<table border="1" >
<tr>
<th>list name</th>
<th>received</th>
<th>student name</th>
</tr>
{% for list_item in list_data %}
<tr>
<td>{{ list_item.serial_number}}</td>
<td>{{ list_item.received}}</td>
<td>{{list_item.studentss}}</td>
</tr>
</table>
{% endblock %}
I have this table in my view which contains large number of data.How do I change these so that I can use scroll down in Django??
Note: I don't want to use pagination to load the data.

I believe this combines the django pagination, but utilizes it in an ajax function to add to the existing page without a reload:
http://django-endless-pagination.readthedocs.org/en/latest/twitter_pagination.html

For Django 1.8 and above use:
Django EL(Endless) Pagination:
This app django-el-pagination created from
django-endless-pagination==2.0.
https://github.com/shtalinberg/django-el-pagination
Django Endless Pagination says:
This project is abandoned.
Thanks to the community that supported django-endless-pagination over
time. I do not have time to properly maintain and develop this
application. From now on, please use one of the great forks like
https://github.com/shtalinberg/django-el-pagination

Related

Check if a link is working and hide/disable if it's broken using HTML/JavaScript

So I am building my website using HTML/CSS.
I would like to know what is the easiest way to check if a URL is availble?
For example, I have a table with a cell that shows a link to some URL -
<table class="table table-hover table-bordered table-condensed" cellspacing="0" width="1300" id="ServerTable">
<thead>
<tr>
<th><center> #</center></th>
<th width="100%"><center> Server Name </center></th>
<th><center> Owner </center></th>
<th><center> Project </center></th>
<th width="100%"><center> Description </center></th>
<th width="100%"><center> IP Address </center></th>
<th width="100%"><center> ILO </center></th>
<th><center> Rack </center></th>
<th><center> Status </center></th>
<th><center> Actions </center></th>
</tr>
</thead>
<tbody>
{% for server in posts %}
<tr>
<div class ="server">
<td></td>
<td width="100%"><center>{{ server.ServerName }}</center></td>
<td width="100%"><center>{{ server.Owner }}</center></td>
<td width="100%"><center>{{ server.Project }}</center></td>
<td width="100%"><center>{{ server.Description }}</center></td>
<td width="100%"><center>{{ server.IP }}</center></td>
<td width="100%"><center> http://{{ server.ServerName }}.ilo.lab.dba.co.il </center></td>
<td width="100%"><center>{{ server.Rack }}</center></td>
<td width="100%"><h4><span class="badge badge-success">Online</span></h4></td></center>
In this cell, there is a link to some url.
I want to show the link as URL (a href) only if http://{{ server.ServerName }}.ilo.lab.dba.co.il is working using http! (server.ServerName is a variable running in a for loop giving different DNS URLS)
If it's not, I will show just a text, or not show it all...
I have found some functions in Javascript that return true and false, but I dont know how to call the function in my html.
Like, I was thinking of doing if (link works) : show link with a href, else: show just the string...
Is it possible using Javascript function? If so, what's the function and how do I call it?
An example for a function I found:
How can I use and test it in my code? using href if it's true?
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status==200;
}
Assuming your page isn't hosted on http://10.0.5.1, there's no general-purpose way to do this from the browser unless the target servers allow it, and separately it's probably not ideal to do so.
If the origin of your target pages isn't the same as the origin of the page, the Same Origin Policy kicks in and prevents your using ajax (XMLHttpRequest, fetch) to check the links. You could work around that if you can implement Cross-Origin Resource Sharing on all of the target servers, telling them to give your page access. But again: Requesting all of the resources linked on the page, even with a HEAD request, is probably not ideal.
You've tagged your question with PHP. You could certainly use PHP to check the links before returning the page. This question's answers show how to do a HEAD request for a URL.
You've also tagged Django, a Python server-side framework. You can do a HEAD request with Python, too; this search turned up this question and its answers.
Due your application backend is Django, I would recommend you using Python to check whether an http based url is available or not.
According to #T. J. Crowder suggested, track of the links/questions to implement the mothod checkUrlAvailable(url) with a URL as the argument.
I've found the documentation of Built-in template tags and filters showing how to apply filters in Django template.
All in all, we can combine all together like the following:
<td width="100%"><center>
{% if checkUrlAvailable(server) is True %}
http://{{ server.ServerName }}.ilo.lab.dba.co.il
{% else %}
http://{{ server.ServerName }}.ilo.lab.dba.co.il
{% endif %}
</center></td>
The problem I am having is to check an non-existing server/url with Python. I will update this issue soon once it would be resolved.
To write checkUrlAvailable in Django template, take a look at the documentation. The idea is to build a customised filter to check the existence of a given URL. The pseudo code could be looked like the following but I argue to dive into these answers:
import requests
def checkUrlAvailable(url):
resp = requests.head(url)
if resp.status_code == 200:
return True
else
return False
I just borrowed the snippet code from stackoverflow's link.
(to be updated soon)

Django Python - Javascript Dynamic Table sorting rows

I have never done any javascript but I saw that this is what I am looking for to display a dynamic table one of my html template.
I have read that there should be something using JQuery but not much more.
So I am looking exactly for an example of dynamic table able to sort rows following which column is selected, written in javascript, displayed in an HTML template, using:
- as columns: the fields of a MySQL table (see example below).
- as rows: the entries contained in the same table
And all of this has to use Django (I don't know if the javascript file either has to be separated from the HTML template or has to be in the HTML template)
Example MySQL table:
CREATE TABLE PDB(
id_PDB_chain CHAR(5) NOT NULL PRIMARY KEY,
id_PDB CHAR(4) NOT NULL,
chaine VARCHAR(10) NOT NULL,
header VARCHAR(255) NOT NULL,
sequence_Proteine TEXT NOT NULL,
start_seq INT NOT NULL,
taille_Proteine INT NOT NULL,
resolution_PDB FLOAT NOT NULL,
meth_Res VARCHAR(10) NOT NULL,
FOREIGN KEY (meth_Res)
REFERENCES methodes_res(meth_Res)
ON DELETE CASCADE
);
Corresponding class in the "models.py" file:
from __future__ import unicode_literals
from django.db import models
class Pdb(models.Model):
id_pdb_chain = models.CharField(db_column='id_PDB_chain', primary_key=True, max_length=5) # Field name made lowercase.
id_pdb = models.CharField(db_column='id_PDB', max_length=4) # Field name made lowercase.
chaine = models.CharField(max_length=10)
header = models.CharField(max_length=255)
sequence_proteine = models.TextField(db_column='sequence_Proteine') # Field name made lowercase.
start_seq = models.IntegerField()
taille_proteine = models.IntegerField(db_column='taille_Proteine') # Field name made lowercase.
resolution_pdb = models.FloatField(db_column='resolution_PDB') # Field name made lowercase.
meth_res = models.ForeignKey('MethodesRes', models.DO_NOTHING, db_column='meth_Res') # Field name made lowercase.
def __unicode__(self):
return self.id_pdb
class Meta:
managed = False
db_table = 'PDB'
In case you need any other informations just ask in comments and I will edit this post with the informations.
In your views.py create a view under whatever name you'd like. Create a list and set it to whatever data you want from your specific model. now go to your template. With that list populated by your specific data you have chosen from the database, use an If statement to check to see if there is anything residing in that list. If there is data there then you can use a For loop like so:
{% for model_name in list_name %}
model_name.model_data etc # Mark it up with relevant html table code, though divs are more preferred
You can mark up the data as needed to display a table, though divs would be more compliant and nicer than tables. This is just a basic example. On the Else statement if no data exists in the list ahead of time, you can simply output that no data exists. Take a look here https://docs.djangoproject.com/en/1.10/intro/tutorial01/
They walk you through building a polling app, where it is relevant to you is the index.html template they build pulling the question data from the database and displaying an unordered list of the questions on the home page as links to vote on. Simply follow this tutorial and look at how they implement the models.py and views.py along with the template and then change the markup from am unordered list to whatever suits your needs.
I found a solution that worked for me and it was really simple in fact:
first you have to download jquery and jquery.tablesorter. Here is the official website where you can download everything and where everything is explained : http://tablesorter.com/docs/
Then, as I work with Django my HTML templates are in a "myapp/templates" directory and my CSS and Javascript files are in a "myapp/static/myapp/" directory.
Here is the template I used:
{% load static %}
<head>
<link rel="stylesheet" type="text/css" href="{% static 'myapp/style.css' %}" />
<script type="text/javascript" src="{% static 'myapp/jquery-3.2.0.min.js' %}">
</script>
<script type="text/javascript" src="{% static 'myapp/jquery.tablesorter.min.js' %}">
</script>
<script type="text/javascript">
$(document).ready(function()
{
$("#pdbtable").tablesorter();
}
);
</script>
</head>
{% if protdb %}
<table id="pdbtable" align="center" border="3" width="100%">
<thead>
<tr>
<th>PDB Id</th>
<th>Chain</th>
<th>Header</th>
<th>Size</th>
<th>Resol.</th>
<th>Method Res.</th>
</tr>
</thead>
<tbody>
{% for i in protdb %}
<tr>
<td>{{ i.id_pdb }}</td>
<td>{{ i.chaine }}</td>
<td>{{ i.header }}</td>
<td>{{ i.taille_proteine }}</td>
<td>{{ i.resolution_pdb }}</td>
<td>{{ i.meth_res }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>No PDBs are available.</p>
{% endif %}
And here is my corresponding view:
def pdbinfo(request):
protdb = Pdb.objects.order_by('id_pdb_chain')\
[:len(Pdb.objects.order_by('id_pdb_chain'))]
context = {
'protdb': protdb
}
return render(request, 'pdbapp/pdbinfo.html', context)
As you maybe know, since you are using Django, your template has to receive all informations from a view in views.py and the table of your database (in my case I use MySQL) have to be filled with entries.
This code is working, take some inspiration from it.
One other content that helped me and that gives more details is a youtube video, check the link here: https://www.youtube.com/watch?v=-wAWfPVXlME&t=334s
I hope it will help!

Combining ng repeat and django template language

I have a table that will have varying columns over time and I want my django view to support those changing columns. I also want to use ng-repeat to do some fancy stuff with it such as filtering and other things. However I am having trouble combining the two.
I am passing in the arbitrary col_names with django template language. packages is also sent in with the django template language and is essentially a json array where each row is a dict mapping col_name to some value. i.e.
$scope.packages = [{'col1': 'row1col1', 'col2': 'row2val2'}, {'col1': 'row2col1' ....
However when I go to put in the rows using packages I can't "nest" my templates. Is there a way to grab arbitrary values out of each row in `packages?
<input ng-model="search" placeholder="Search">
<table style="width:100%;">
<thead>
<tr>
<th>Permanent Column 1</th>
<th>Permanent Column 2</th>
{# changing columns #}
{% for col_name in col_names %}
<th>{{ col_name }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
<tr ng-repeat="package in packages | filter:searchPackage">
{% for col_name in columns %}
<td>{{package.{{ col_name }}}}</td> DOESN'T WORK!
{% endfor %}
</tr>
</tbody>
</table>
In that problem line I essentially want to have {{package.ACTUAL_ARBITRARY_COL_NAME}} but I don't know how to do that programmatically
The problem
By default, Django and AngularJS use the same tokens {{ and }} for templating.
So this gets first processed by Django template
{% for col_name in columns %}
<td>{{package.{{ col_name }}}}</td> DOESN'T WORK!
^ ^
|________________________|
Django template will try to process this value
Because Django tries to expand what's inside the first {{...}}, you will not get what you want AngularJS to see.
If you want to continue down that road, I suggest you read some solutions to this problem here
Better solution
A better approach is to give AngularJS the items you want Django to loop for you.
$scope.columns = [...];
Then use AngularJS to do all the loops. Whichever way you do it, if you need it done in AngularJS, better do it all in AngularJS and not half-Django half-AngularJS.

Vue js and Data Table Panigation not Working

Ok, so unfortunately I have come across this issue. So first a little about specs of my app.
I am using
Vue.js
vue-resource.js
jQuery
jQuery DataTables
Now because I'm grabbing the data through vue-resource, for some reason when the ajax call is final finished and vue imports the data to the table, datatables decides not to render pagination, and displays all 200 results on one page. Is there anyway to refresh datatables so it is rendered with pagination after it has been imported into the table?
My ajax call:
this.$http.get('getDispachedEmails', function(data){
console.log(data['orders']);
this.customers.push(data['orders']);
var dt = $('#myTable').DataTable();
});
My Table:
<table id="myTable" class="u-full-width">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Sex</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<tr v-repeat="customers[0]">
<td>#{{ firstName }} #{{ lastName }}</td>
<td>#{{ email }}</td>
<td>#{{ trackingNumber }}</td>
<td>#{{ address }}</td>
</tr>
</tbody>
</table>
EDIT
I have found out that none of the functions work. If i try to select any row, the table is instantly cleaned. My model (vue model) still has all the objects inside.
SOLUTION:
I just set a wait time to initiate data tables after I collect the data via ajax request. It's a little ghetto, but a least it works. If I find a better fix Ill edit this post.
this.$http.get('getDispachedEmails', function(data){
console.log(data['orders']);
this.customers.push(data['orders']);
setTimeout(function(){$('#myTable').DataTable();}, 5000);
});
A delay of 0 did the trick for me, although not sure why.
setTimeout(function(){$('#myTable').DataTable();}, 0);
I've built a dedicated vue grid component: vue-tables . You might want to check it out.

How to refresh a table in template of Django

I am currently obtaining an object from my views and displaying it in the template in form of a table. Currently I am struck at the part that we need to refresh the table/div, without refreshing the page.
In my views.py
def foo(request):
testruns......
render_to_response('pages/bar.html', locals(), context_instance=RequestContext(request))
My bar.html (template)
<div id = "roman">
{% for trun in testruns %}
<tr>
<td>{{ trun.testprofile }}</td>
<td>{{ trun.time }}</td>
<td>{{ trun.testresult }}</td>
<td>{{ trun.state }}</td>
</tr>
{% endfor %}
</div>
There are two approaches which are supposed to work:
Using dajaxice
Using [Jquery]
$.ajax({
url: '{% url myview %}',
success: function(data) {
$('#the-div-that-should-be-refreshed').html(data);
}
});
I would like to know which approach is more suitable to my case. Using Approach 2, would the table auto refresh, and how do we set the time to refresh ?
Both acceptable but disadvantages of the second approach(pulling table from django as html ):
Carried data over network is much bigger
If u use something javascript based components in your table (maybe
dojo based buttons etc.) they may cause some problems. I had a
smilar issue in dojo and i found the solution in make dojo reparse
the applied html. But life could not be easy everytime so first
approach is better.
If this is only place where you need an auto-refresh, your approach 2 should work along with setting a timer to do the auto-refresh. You can use the setInterval function for the purpose:
// Refresh the Table every 5 seconds
setInterval(function(){
$.ajax({
url: '{% url myview %}',
success: function(data) {
$('#the-div-that-should-be-refreshed').html(data);
}
});
}, 5000)
But if you are planning on developing a responsive webpage, where the whole UI needs to be kept updated, then I would suggest to use a full fledged framework like ember.js

Categories