Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django: auto generate list view with search (admin style)

Tags:

list

django

view

What is the easiest way to generate list view for a model, with clickable headers and search (filter) field, more-or-less like the admin site? I read a bit about generic views, but I don't see a simple solution there.

like image 632
Tomer Avatar asked Oct 14 '22 05:10

Tomer


1 Answers

Generic views are perfect for creating that kind of functionality. Table sorting, searching and pagination can then be performed on client-side using javascript plugins like jQuery and DataTables.

To accomplish that you need to define a generic view and include it in the 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. Code below displays a table with 3 columns and initializes the DataTables plugin. Pagination buttons and search input will be added and header cells will be clickable in order to sort by given 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>
like image 103
Mariusz Jamro Avatar answered Oct 20 '22 17:10

Mariusz Jamro