【问题标题】:display data in tables in django在 django 的表中显示数据
【发布时间】:2020-01-05 11:06:01
【问题描述】:

我已经缩小到以下内容,如果有人可以帮助我指出如何将以下内容转换为很棒的表格视图。以下html是从base.html扩展而来的

{% block page_content %}


<h1>Projects</h1>
<div class="row">
{% for project in projects %}
    <div class="col-md-4">
       <div class="card mb-2">
            <img class="card-img-top" src="{% static project.image %}">
            <div class="card-body">
                <h5 class="card-title">{{ project.title }}</h5>
                <p class="card-text">{{ project.description }}</p>
                <a href="{% url 'project_detail' project.pk %}"
                   class="btn btn-primary">
                    Read More
                </a>

            </div>
        </div>
    </div>
    {% endfor %}
</div>
{% endblock %}

在 gridview 中显示数据时需要帮助。我对这一切都很陌生。我可以从 mongodb 读取和显示页面上的数据,但需要在表格中显示。

现在对我来说百万美元的问题是我应该在哪里调整代码中的以下 sn-p 以提供 gridview

<table>
    <tr>
        <th>Field 1</th>
        <th>Field N</th>
    </tr>
    {% for item in query_results %}
    <tr> 
        <td>{{ item.field1 }}</td>
        ...
        <td>{{ item.fieldN }}</td>
    </tr>
    {% endfor %}
</table>

我的 urls.py

from django.urls import path
from .import views

urlpatterns = [
    path("",views.project_index, name = "project_index"),
    path ("<project_detail>/",views.project_detail, name = "project_detail"),
    #path("<int:pk>/", views.project_detail, name = "project_detail"),
]

我的模型.py

from django.db import models

# Create your models here.
class Project(models.Model):
    title = models.CharField(max_length=100,primary_key=True)
    desc = models.CharField(max_length=100)
    urls = models.CharField(max_length=100)
    #image = models.FilePathField(path="/img")

    class Meta:
        db_table = "spiderCollection1"

附加表.py

import django_tables2 as tables
from .models import Project
import itertools

class ProjectTable(tables.Table):
    class Meta:
        model = Project
        template_name = "django_tables2/bootstrap.html"
        title = tables.Column("title")
        desc = tables.Column("desc")
        urls = tables.Column("urls")

下面是views.py

from django_tables2 import SingleTableView
from django.shortcuts import render
from projects.models import Project
from projects.tables import ProjectTable

# Create your views here.
class ProjectListView(SingleTableView):
    model = Project
    table_class = ProjectTable
    template_name = '/projects.html'

def project_index(request):
    projects = Project.objects.all()
    context = {
        "projects":projects
    }
    return render (request, 'project_index.html',context)
    #return render (request, 'project_index.html',locals())

def project_detail(request, pk):
    #project = Project.objects.get(pk=pk)
    project = Project.objects.all()
    context = {
        "project": project
        #'personal_portfolio':project
    }
    return render(request, 'project_detail.html',context)

我的主要 base.html

<nav class="navbar navbar-expand-lg navbar-light bg-light">
    <div class="container">
        <a class="navbar-brand" href="{% url 'project_index' %}">Portfolio</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse" id="navbarSupportedContent">
          <ul class="navbar-nav mr-auto">

              <li class="nav-item active">
              <a class="nav-link" href="{% url 'project_index' %}">Home</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">Blog</a>
            </li>
          </ul>
        </div>
    </div>

    <!--<style>
        h1 {
            border: 5px solid red;
            }

        h2 {
            border: 4px dotted blue;
            }
        div {
            border: double;
            }
      </style>
      -->


</nav>

<div class="container">
    {% block page_content %}
    {% endblock %}
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

现在是 project_index.html

{% extends "base.html" %}
{%load render_table from django_tables %}
{% load static %}
{% block page_content %}


<h1>Projects</h1>
<div class="row">
{% for project in projects %}
    <div class="col-md-4">
       <div class="card mb-2">
            <img class="card-img-top" src="{% static project.image %}">
            <div class="card-body">
                <h5 class="card-title">{{ project.title }}</h5>
                <p class="card-text">{{ project.description }}</p>
                <a href="{% url 'project_detail' project.pk %}"
                   class="btn btn-primary">
                    Read More
                </a>
            </div>
        </div>
    </div>


    {% endfor %}
</div>
{% endblock %}

【问题讨论】:

  • 您的 html 文件应该呈现表格。您加载了 django_tables,但看起来您实际上并没有在任何地方显示该表。查看 django_table 文档,了解在 html 文件中呈现表格。
  • 这就是我遵循django-tables2.readthedocs.io/en/latest/pages/tutorial.html 的 django tables2 文档所做的事情。但我坚持使用gridview而不是listview。可以建议我该怎么做才能以gridview或表格格式显示?请建议

标签: django python-3.x django-tables2


【解决方案1】:

如果目标是在不使用 django-table2 包的情况下显示表格,请遵循答案的第一部分。如果目标是使用 django-table2 则跳转到第二部分:

第一部分

根据您的要求,让我们使用示例 sn-p,并对其进行编辑,以便在 HTML 表格中显示您的 project 数据...

从你的project_index.html开始,我们需要使用&lt;table&gt;&lt;thead&gt;&lt;tbody&gt;&lt;th&gt;标签创建html表的骨架,然后循环传递的projects上下文变量和使用&lt;td&gt; 标记将条目添加到表中。而且因为您使用的是引导框架,所以我们需要行和列 divss 才能正确显示表格。

{% extends "base.html" %}
{% load static %}

{% block page_content %}

<h1>Projects</h1>
<div class="row">
    <div class="col-md-4"> 
        <table class="table table-striped table-hover">
        <thead>
            <th>#</th>
            <th>title</th>
            <th>description</th>
        </thead>
        <tbody>
        {% for project in projects %}
           <td><strong>{{ forloop.counter }} </strong></td>
           <td><strong>{{ project.title}</strong></td>
           <td>{{ project.description} <a href="{% url 'project_detail' project.pk %}" class="btn btn-primary">Read More</a> </td>
        {% endfor %}
        </tbody>
        </table>
    <div>
</div>
{% endblock %}

确保您的url.py 指向函数project_index

要了解更多信息,请查看:

第二部分

Django-table2 是一个包,它提供了一个应用程序和中间件来生成 html 表。为了在您的应用中使用它,请对您的 project_index.html 进行以下更改:

{% extends "base.html" %}
{% load render_table from django_tables %}
{% load static %}
{% block page_content %}


<h1>Projects</h1>
<div class="row">
    <div class="col-md-4">
    {% render_table projects %}
    </div>
</div>
{% endblock %}

上面的代码将使用 django-table2 提供的 html 模板来渲染表格,在你的类 ProjectTable 中定义

class ProjectTable(tables.Table):
    class Meta:
        model = Project
        template_name = "django_tables2/bootstrap.html"  
        ...

如果您想使用自定义渲染,您需要将 ProjectTable 的 template_name 设置为您的 custom.html:

 class ProjectTable(tables.Table):
    class Meta:
        model = Project
        template_name = "custom.html"  
        ...

现在创建custom.html 并添加将实际迭代项目上下文变量项的代码。可能是这样的(从 django_tables2/semantic.html 复制)...对此模板进行您想要的更改。

{% load django_tables2 %}
{% load i18n %}
{% block table-wrapper %}
<div class="ui container table-container">
    {% block table %}
        <table {% render_attrs table.attrs class="ui celled table" %}>
            {% block table.thead %}
            {% if table.show_header %}
                <thead {{ table.attrs.thead.as_html }}>
                    <tr>
                    {% for column in table.columns %}
                        <th {{ column.attrs.th.as_html }}>
                            {% if column.orderable %}
                                <a href="{% querystring table.prefixed_order_by_field=column.order_by_alias.next %}">{{ column.header }}</a>
                            {% else %}
                                {{ column.header }}
                            {% endif %}
                        </th>
                    {% endfor %}
                    </tr>
                </thead>
            {% endif %}
            {% endblock table.thead %}
            {% block table.tbody %}
                <tbody {{ table.attrs.tbody.as_html }}>
                {% for row in table.paginated_rows %}
                    {% block table.tbody.row %}
                    <tr {{ row.attrs.as_html }}>
                        {% for column, cell in row.items %}
                            <td {{ column.attrs.td.as_html }}>{% if column.localize == None %}{{ cell }}{% else %}{% if column.localize %}{{ cell|localize }}{% else %}{{ cell|unlocalize }}{% endif %}{% endif %}</td>
                        {% endfor %}
                    </tr>
                    {% endblock table.tbody.row %}
                {% empty %}
                    {% if table.empty_text %}
                    {% block table.tbody.empty_text %}
                    <tr><td colspan="{{ table.columns|length }}">{{ table.empty_text }}</td></tr>
                    {% endblock table.tbody.empty_text %}
                    {% endif %}
                {% endfor %}
                </tbody>
            {% endblock table.tbody %}
            {% block table.tfoot %}
            <tfoot {{ table.attrs.tfoot.as_html }}>
                {% if table.has_footer %}
                <tr>
                {% for column in table.columns %}
                    <td {{ column.attrs.tf.as_html }}>{{ column.footer }}</td>
                {% endfor %}
                </tr>
                {% endif %}
                {% block pagination %}
                    {% if table.page and table.paginator.num_pages > 1 %}
                    <tr>
                    <th colspan="{{ table.columns|length }}">
                        <div class="ui right floated pagination menu">
                            {% if table.page.has_previous %}
                                {% block pagination.previous %}
                                <a href="{% querystring table.prefixed_page_field=table.page.previous_page_number %}" class="icon item">
                                    <i class="left chevron icon"></i>
                                </a>
                                {% endblock pagination.previous %}
                            {% endif %}

                            {% if table.page.has_previous or table.page.has_next %}
                                {% block pagination.range %}
                                    {% for p in table.page|table_page_range:table.paginator %}
                                        {% if p == '...' %}
                                            <a href="#" class="item">{{ p }}</a>
                                        {% else %}
                                            <a href="{% querystring table.prefixed_page_field=p %}" class="item {% if p == table.page.number %}active{% endif %}">
                                                {{ p }}
                                            </a>
                                        {% endif %}
                                    {% endfor %}
                                {% endblock pagination.range %}
                            {% endif %}

                            {% if table.page.has_next %}
                                {% block pagination.next %}
                                <a href="{% querystring table.prefixed_page_field=table.page.next_page_number %}" class="icon item">
                                    <i class="right chevron icon"></i>
                                </a>
                                {% endblock pagination.next %}
                            {% endif %}
                        </div>
                    </th>
                    </tr>
                    {% endif %}
                {% endblock pagination %}
            </tfoot>
            {% endblock table.tfoot %}
        </table>
    {% endblock table %}
</div>
{% endblock table-wrapper %}

在此确保您的urls.py 包括:

...
path("projects/", ProjectListView.as_view())
...

更多参考:

【讨论】:

  • 嘿,非常感谢您向我解释,非常感谢。但我看到了同样的结果。任何想法都可以缺少什么。我清除了缓存。重新启动了应用程序。还要别的吗。实际上我使用了你给定的文件但没有用:( ...让我紧张......我有一种直觉,我很接近。
  • 好的,我发现了另一个问题, - 页面显示来自 base.html 的所有内容 - 不知何故 project_index.html 甚至没有呈现。我在 project_index.html 中输入的内容甚至都没有显示在页面上。应该怎么做才能解决这个问题?还有什么可能错过的?
  • 嗯,好的。您能否分享您的路由文件:url.py 请将其添加到原始问题中!
  • 所以...您将本机 Django 代码与 django-table2 代码混合在一起,我的建议是停止使用 django-table2 代码,直到您对 Django 有所控制。所以在你的 urls.py 替换: path("projects/", ProjectsListView.as_view()) 为: path("projects/", project_index)
  • 我已经编辑了我的答案以包括本机 Django 代码的情况,第二个使用 Django-table2 包。我希望这可以帮助您进一步...
【解决方案2】:
<div class="center">
<table class="table table-bordered " border="1">
    <tr>
        <th>Name</th>
        <th>Game</th>
    </tr>
    {% for i in user_data %}
        <tr>
            <td>{{i.name}}</td>
            <td>{{i.favorite_game}}</td>
        </tr>
    {% endfor %}</table>

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 2015-11-21
  • 2015-05-06
  • 2011-07-10
  • 1970-01-01
  • 2022-11-15
  • 2011-11-09
  • 1970-01-01
  • 2020-11-28
相关资源
最近更新 更多