Reputation: 1355
I am wanting to select only a few fields in a Django_Table2 element. I have been looking at the django_table2 website django_table2 and I can't find much on how to limit the number of fields are used in a django_table2 element. Here is my code.
This is my Project view.py:
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone
from .models import Project
class IndexView(generic.ListView):
model = Project.objects.values("id","name","jobNumber", "contractor", "assigned_to", "created_date")
template_name = 'project/index.html'
def get_queryset(self):
return Project.objects.values("id","name","jobNumber", "contractor", "assigned_to", "created_date")
class DetailView(generic.DetailView):
model = Project
template_name = 'project/detail.html'
This is my index.html template:
{% load render_table from django_tables2 %}
{% block content %}
<h1>Projects</h1>
<ul>
{% for project in project_list %}
<li><a href="{% url 'project:detail' project.id %}">{{ project.name }}</a></li>
{% endfor %}
</ul>
{% render_table project_list %}
{% endblock %}
How do I limit the number of fields/columns being displayed with django_tables2?
Upvotes: 2
Views: 1272
Reputation: 2143
one way to go is to have the table class and add a meta exclude to remove the columns you want:
class MyTable(tables.Table):
class Meta:
model = MyModel
exclude = ('unwanted_col', 'unwanted_col2',)
Then in the view logic have:
table = MyTable(data_list)
RequestConfig(request).configure(table)
return render(request, 'myapp/index.html', {'table': table})
The imports in use in my views.py file that contains this code that are relevant to the snipits:
import django_tables2 as tables
from django_tables2.config import RequestConfig
from django.shortcuts import render
and in the index html have the render table.
Upvotes: 1