Django: automatically create a list using search (admin style)

What is the easiest way to create a list view for a model with clickable headers and a search (filtering) field more or less like an admin site? I read a little about general ideas, but I don’t see a simple solution there.

+4
source share
1 answer

General views are ideal for creating such functionality. Then sorting, searching and paging can be done on the client side using javascript plugins such as jQuery and DataTables .

To do this, you need to define a general view and include it in urls.py:

from django.views.generic import ListView from exampleapp.models import BlogPost class BlogPostListView(ListView): """"Class that extends generic ListView""" template_name = "list.html" def get_queryset(self): return BlogPost.objects.filter(published=True) urlpatterns = patterns('', url('^list/$', BlogPostListView.as_view() ), ) 

Everything else is done in the template file. The code below shows a table with three columns and initializes the DataTables plugin. The pagination and search entry buttons will be added, and the header cells will be available for viewing to sort by the specified column.

 <script type="text/javascript" language="javascript" src="http://datatables.net/release-datatables/media/js/jquery.js"></script> <script type="text/javascript" language="javascript" src="http://datatables.net/release-datatables/media/js/jquery.dataTables.js"></script> <script> $(document).ready(function(){ // Initalize DataTables on <table> tag with id="example" $('#example').dataTable(); }); </script> <table id="example"> <thead> <!-- header row --> <tr> <td>ID</td> <td>column1</td> <td>column2</td> </tr> </thead> <tbody> <!-- data --> {% for item in object_list.all %} <tr> <td>{{ item.id }}</td> <td>{{ item.column1 }}</td> <td>{{ item.column2 }}</td> </tr> {% endfor %} </tbody> </table> 
+3
source

Source: https://habr.com/ru/post/1309988/


All Articles