Python – Use django_tables2 to add CSS styles to tables in django

Use django_tables2 to add CSS styles to tables in django… here is a solution to the problem.

Use django_tables2 to add CSS styles to tables in django

I’m new to Django. I’m trying

to add CSS styles to the table at

{% render_table table %}

Running.

The code is as follows:

views.py:

def myTable(request):
    table = myDataTable.objects.all()
    filter = request. GET.get('q')
    startDate = request. GET.get('sd')
    endDate = request. GET.get('ed')
    if mail:
        table = table.filter(Q(filter__icontains=filter) &
                         Q(evaluation_date__range=[startDate, endDate])).distinct()
    else:
        table = table.filter(Q(evaluation_date__range=[startDate, endDate])).distinct()
    table = TableView(table)
    RequestConfig(request).configure(table)
    return render(request, 'myapp/myTable.html', {'table': table})

Form .py:

class TableView(tables. Table):
      class Meta:
           model = myDataTable
           template = 'django_tables2/bootstrap.html'

My app .html

{% load staticfiles %}
{% load render_table from django_tables2 %}
....
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
....
<body>
     {% render_table table %}

I have a custom style file customstyle .css in project/static/css/, but there is no way to get the rendered table to use that style.

Can you help me?

Solution

I

struggled to get the right style for the table I’m also rendering :

{% render_table table %}

In your tables.py file, you can set the properties of the table itself, such as its class, as follows:

class TableView(tables. Table):
    class Meta:
        attrs = {'class': 'table table-striped table-hover'}

Related Problems and Solutions