【问题标题】:Displaying a Table in Django from Database从数据库中显示 Django 中的表
【发布时间】:2011-11-09 08:44:06
【问题描述】:

如何在网页上以表格格式显示数据库表格中的信息?在 django 中是否有一种简单的方法可以做到这一点,还是需要更复杂的方法。更具体地说,您如何将数据库表中的列和行移植到可以从 url 看到的可视表?

【问题讨论】:

    标签: django database


    【解决方案1】:

    如果你想表格,请执行以下步骤:-

    views.py:

    def view_info(request):
        objs=Model_name.objects.all()
        ............
        return render(request,'template_name',{'objs':obj})
    

    .html 页面

     {% for item in objs %}
        <tr> 
             <td>{{ item.field1 }}</td>
             <td>{{ item.field2 }}</td>
             <td>{{ item.field3 }}</td>
             <td>{{ item.field4 }}</td>
        </tr>
           {% endfor %}
    

    【讨论】:

      【解决方案2】:
      $ pip install django-tables2
      

      settings.py

      INSTALLED_APPS , 'django_tables2'
      TEMPLATES.OPTIONS.context-processors , 'django.template.context_processors.request'
      

      models.py

      class hotel(models.Model):
           name = models.CharField(max_length=20)
      

      views.py

      from django.shortcuts import render
      
      def people(request):
          istekler = hotel.objects.all()
          return render(request, 'list.html', locals())
      

      list.html

      {# yonetim/templates/list.html #}
      {% load render_table from django_tables2 %}
      {% load static %}
      <!doctype html>
      <html>
          <head>
              <link rel="stylesheet" href="{% static 
      'ticket/static/css/screen.css' %}" />
          </head>
          <body>
              {% render_table istekler %}
          </body>
      </html>
      

      【讨论】:

        【解决方案3】:

        最简单的方法是使用for loop template tag

        鉴于观点:

        def MyView(request):
            ...
            query_results = YourModel.objects.all()
            ...
            #return a response to your template and add query_results to the context
        

        您可以在模板中添加这样的 sn-p...

        <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>
        

        这在 Django 教程的Part 3 中都有介绍。如果您需要从那里开始,这里是Part 1

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-14
          • 1970-01-01
          相关资源
          最近更新 更多