Package: django-jquery-datatables
Django jQuery DataTablesDjango jQuery DataTables is a Python library that integrates the popular jQuery DataTables library with Django projects. It provides a convenient way to handle and manage datatables in your Django application.FeaturesIntegration with jQuery DataTables for efficient data table handling.Support for main search and individual column search.Flexible column remapping for customized data filtering.Pagination support for large datasets.Easy serialization of data using Django serializers.InstallationYou can install Django jQuery DataTables usingpip install django_jquery_datatables:UsageTo use Django jQuery DataTables in your Django project, follow these steps:Install Django jQuery DataTables bypip install django_jquery_datatables.Import the main datatables function by usingfrom django_jquery_datatables.utils import JqueryDatatableThis JqueryDatatable is used in the view function of django, it returns all the data required by jquery datatables library in the form of JSON.Basic Example#####Frontend:<tableid="users_table"class="table"><thead><tr><th>Username</th><th>Is Staff</th><th>Is Superuser</th><th>Is Active</th><th>Last Login</th></tr></thead></table><script>$(document).ready(function(){$('#users_table').DataTable({dom:'Bfrtip',order:[],orderCellsTop:true,"processing":true,"serverSide":true,ajax:{url:'/django_jquery_datatable_url/',type:'GET',contentType:'application/json',},columns:[{data:"username"},{data:"is_staff"},{data:"is_superuser"},{data:"is_active"},{data:"last_login"},],"createdRow":function(row,data,dataIndex){$(row).attr("id",data.id);},buttons:['copy','csv','excel','pdf','print','pageLength'],lengthMenu:[[10,50,100,500],["10 rows","50 rows","100 rows","500 rows"],],pageLength:10,});});</script>Django Backendfromdjango.contrib.auth.modelsimportUserfromdjango_jquery_datatables.utilsimportJqueryDatatablefromrest_frameworkimportserializersclassUsersSerializer(serializers.ModelSerializer):DT_RowId=serializers.IntegerField(source='id')classMeta:model=Userexclude=['password']defmy_view(request):queryset=User.objects.all()# You can also sort the initial data here.returnJqueryDatatable(request,queryset,UsersSerializer)Advance Examples1. Individual Column SearchFor adding search to each individual column in datatables, there is no need to change backend logic, you only need to
add search to your jquery code, here is an example usage with seach at the top of every column.<tableid="users_table"class="table"><thead><tr><th>Username</th><th>Is Staff</th><th>Is Superuser</th><th>Is Active</th><th>Last Login</th></tr></thead></table><script>$(document).ready(function(){$('#users_table thead tr').clone(true).appendTo('#users_table thead');$('#users_table thead tr:eq(1) th').each(function(i){vartitle=$(this).text();// Here you can specify the column names on which you do not want to add a searchif(['Remove','Edit','Action'].includes(title)){$(this).html('');}else{$(this).html(`<div class="col-xs-2"><input style="height:10px;" name="${title}" placeholder="Search" class="form-control" type="text"></div>`);$('input',this).on('keyup change',function(){if(table.column(i).search()!==this.value){table.column(i).search(this.value).draw();}});}});vartable=$('#users_table').DataTable({dom:'Bfrtip',order:[],orderCellsTop:true,"processing":true,"serverSide":true,ajax:{url:'/django_jquery_datatable_url/',type:'GET',contentType:'application/json',},columns:[{data:"username"},{data:"is_staff"},{data:"is_superuser"},{data:"is_active"},{data:"last_login"},],"createdRow":function(row,data,dataIndex){$(row).attr("id",data.id);},buttons:['copy','csv','excel','pdf','print','pageLength'],lengthMenu:[[10,50,100,500],["10 rows","50 rows","100 rows","500 rows"],],pageLength:10,});});</script>Backend code remains the same as provided previously2. Custom Columns MapingThis feature is very handful when you're having a custom field defined in your
serializer which is not present in your database, by doing this search will be done using 'bar' which is present in your model.To do this you can simple pass and array of python dict with the name of field and the model field in values.returnJqueryDatatable(request,queryset,UsersSerializer,[{'foo':'bar'}])a) Maping single columnIn this example you can map one column which is defined in your serializer to any column present in your model
For Example:A field named 'foo' is defined in serializer which you want to map with a field 'bar' in your model you can map it as:fromdjango.contrib.auth.modelsimportUserfromdjango_jquery_datatables.utilsimportJqueryDatatablefromrest_frameworkimportserializersclassUsersSerializer(serializers.ModelSerializer):DT_RowId=serializers.IntegerField(source='id')foo=serializers.SerializerMethodField()classMeta:model=Userexclude=['password']defget_foo(self,obj):return'Hello World'defmy_view(request):queryset=User.objects.all()# You can also sort the initial data here.returnJqueryDatatable(request,queryset,UsersSerializer,[{'foo':'bar'},])b) Maping multiple columnsPreviously we've discussed how you can map a field with one field present in models, but if there is a field defined in your serializer which is a combination of two or more other field and you want to map them to multiple fields, then you can use this method.For Example:If you've defined a field 'full_name' which is a combination of three field defined in your models 'first_name', 'middle_name' and 'last_name'Models:fromdjango.dbimportmodelsclassUser(models.Model):first_name=models.CharField(max_length=50,null=True)middle_name=models.CharField(max_length=50,null=True)last_name=models.CharField(max_length=50,null=True)bar=models.CharField(max_length=50,null=True)Serializer and View:fromdjango.contrib.auth.modelsimportUserfromrest_frameworkimportserializersfromdjango_jquery_datatables.utilsimportJqueryDatatableclassUsersSerializer(serializers.ModelSerializer):DT_RowId=serializers.IntegerField(source='id')full_name=serializers.SerializerMethodField()foo=serializers.SerializerMethodField()classMeta:model=Userexclude=['password']defget_foo(self,obj):return'Hello World'defget_full_name(self,obj):returnf'{obj.first_name}{obj.middle_name}{obj.last_name}'defmy_view(request):queryset=User.objects.all()# You can also sort the initial data here.returnJqueryDatatable(request,queryset,UsersSerializer,[{'foo':'bar'},{'full_name':['first_name','middle_name','last_name']},])ContributingContributions are welcome! If you find a bug or have a suggestion, please open an issue on the issue tracker.If you want to contribute code, please fork the repository, create a new branch for your changes, and submit a pull request.LicenseThis library is licensed under the MIT License.