简体   繁体   中英

Django Django_Tables2 Fields

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?

The tutorial says "While simple, passing a queryset directly to {% render_table %} doesn't allow for any customisation. For that, you must define a Table class." The API shows that Table.Meta has fields and excludes attributes, similar to ModelForms.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM