Search code examples
djangodjango-tables2

How do I use django_tables2 with a filter?


I'm displaying data on a webpage, and I would like to migrate this code to use the table I created in tables.py. I can't figure out how to do it without breaking the filter.

views.py

def PlatListView(request):
    
    queryset = Plat.objects.all().values('id', 'description','status', 'phase__number','phase','schedule_found').annotate(lot_count=Sum('phase__lot_count')).order_by('description')

    f = PlatFilter(request.GET, queryset=queryset)
   
    return render(request, 'blog/filtertable2.html', {'filter': f})

filters.py

class PlatFilter(django_filters.FilterSet):
    community = ModelChoiceFilter(queryset=Community.objects.all())

tables.py

import django_tables2 as tables

class PlatTable(tables.Table):  

    id = tables.Column()
    description = tables.Column()
    status = tables.Column()
    phase__number = tables.Column()
    lot_count = tables.Column()
    schedule_found = tables.Column()
    
    class Meta:
        ordering = 'description'
        #model = Plat

filtertable2.html

{% extends "blog/base.html" %}
{% block content %}

{% load bootstrap4 %}

<form method="get">
        {{ filter.form.as_p }}
        <input type="submit" />
    </form>

 <table>
  <tr>
    <th>Description</th>
    <th>Status</th>
  </tr>
 {% for obj in filter.qs %}
  <tr>
    
        <td> {{ obj.description }}</td>
        <td>{{ obj.status }}</td>
   
  </tr>
   {% endfor %}
</table>
   
{% endblock content %}

Solution

  • In your view you construct the table with the data from the filter:

    def PlatListView(request):
        queryset = Plat.objects.annotate(
            lot_count=Sum('phase__lot_count')
        ).order_by('description')
    
        f = PlatFilter(request.GET, queryset=queryset)
        table = PlatTable(data=f.qs)
        return render(request, 'blog/filtertable2.html', {'filter': f, 'table': table})

    You can then render the table with:

    {% extends "blog/base.html" %}
    {% block content %}
    
    {% load bootstrap4 %}
    {% load render_table from django_tables2 %}
    
    <form method="get">
        {{ filter.form.as_p }}
        <input type="submit" />
    </form>
    
    {% render_table table %}
       
    {% endblock content %}