jQuery’s plug-in dataTables is an excellent table plug-in that provides table sorting, browser paging, server paging, filtering, formatting and other functions.
How to display the data in the database to the front end in the form of a table. There are many ways to achieve it. Recently, I used jquery’s datatables plug-in to realize it and found that it is relatively simple. Today we will look at an example to illustrate the use of this plug-in. , the basic principle is that the view function reads data from the database, jquery obtains the data through ajax and displays it on the front end. We first define a models.py, as follows:
from django.dbimport models class MyModel(models.Model): someAttr = models.CharField() def __unicode__(self): return self.someAttr
Then define our view function:
fromdjango.httpimportHttpResponse fromdjango.coreimportserializers from .modelsimportMyModel defmyModel_asJson(request): object_list = MyModel.objects.all() json = serializers.serialize('json', object_list) return HttpResponse(json, content_type='application/json')
Because datatables receives data in json format, the data read from the database must be serialized, which is this sentence:
json = serializers.serialize(‘json', boject_list)
Add the following url.py:
from django.conf.urlsimport patterns, url urlpatterns = patterns('myapp.views', url(regex=r'^$', view='myModel_asJson', name='my_ajax_url'), )
The last is the content of the template file:
<tablecellpadding="0" cellspacing="0" border="0" id="example"> <thead> <tr><th>My Attr Heading</th></tr> </thead> <tbody></tbody> </table> <scripttype="text/javascript" language="javascript" class="init"> $(document).ready(function() { $('#example').dataTable( { "processing": true, "ajax": { "processing": true, "url": "{% url 'my_ajax_url' %}", "dataSrc": "" }, "columns": [ { "data": "fields.someAttr }, { "data": "pk" } ] } ); } ); </script>
The url specifies the name of your view function, and columns specifies the columns to be displayed, so that the data is displayed in the form of a table. If you want it to be beautiful, remember to style it yourself. Bootstrap is recommended, and datatables loads all the data at once. The front end handles it, so if you load a lot of entries, there will be a sense of pause, and the bServierSide parameter must be added.
The editor will introduce you to the jQuery plug-in datatables usage tutorial here. I hope it will be helpful to you!