简体   繁体   English

Django Django_Tables2 字段

[英]Django Django_Tables2 Fields

I am wanting to select only a few fields in a Django_Table2 element.我只想在 Django_Table2 元素中选择几个字段。 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.我一直在查看 django_table2 网站django_table2 ,但我找不到太多关于如何限制 django_table2 元素中使用的字段数量的信息。 Here is my code.这是我的代码。

This is my Project view.py:这是我的项目 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:这是我的 index.html 模板:

{% 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?如何限制使用 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."教程说“虽然简单,但将查询集直接传递给 {% render_table %} 不允许进行任何自定义。为此,您必须定义一个 Table 类。” The API shows that Table.Meta has fields and excludes attributes, similar to ModelForms. API显示 Table.Meta 具有字段和排除属性,类似于 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:我的 views.py 文件中使用的导入包含与 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.并在索引 html 中有渲染表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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