【问题标题】:Generate Table Columns automatically on Django with view使用视图在 Django 上自动生成表列
【发布时间】:2022-07-23 02:35:07
【问题描述】:

我正在使用 django,我正在根据教程数据创建一个表。 当我正在构建我的 .html 时,我很容易得到一个循环来从我的选择实例中写入数据,但我无法让相同的东西为列名工作。 我在这里看到了如何get the model fields,但我无法获得一个循环来为我编写它们。

table.html

{% extends 'base.html'%}

{% block content%} 
<div class="container">
    <div class="row">
      <p><h3 class="text-primary"> Python Django DataTables </h3></p>
      
<hr style="border-top:1px solid #000; clear:both;" />
<table id = "myTable" class ="table table-bordered">
    <thead class = "alert-warning"> 
        <tr>
<!-- i would like not to have to write those one by one for future projects --> 
            <th> Choice </th> 
            <th> Votes </th>
        </tr>
    </thead> 
    <tbody>
<!-- this is the kind of loop I wanted for the columns--> 
        {% for item in qs %} 
        <tr> 
            <td contenteditable='true'>{{item.choice_text}}</td>
            <td>{{item.votes}}</td>  

        </tr>
        {% endfor %}
    </tbody>
</table>

{% endblock content%}

views.py

class ChoiceTableView(TemplateView):
    model = Question
    template_name = 'polls/table.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["qs"] = Choice.objects.all()
        return context

models.py

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    
    def __str__(self):
        return self.choice_text

【问题讨论】:

  • 您能否添加一些有关您得到的错误类型或不良结果的详细信息?

标签: python django


【解决方案1】:

如果您想要一个可以完全自动打印标题和值的模板,您可以使用不同的查询集:

context["qs"] = Choice.objects.all().values( 'the', 'fields', 'you', 'want')

在模板中,每个“对象”都是一个字典{'the':value_of_the, 'fields':..., ...}。所以,object.keys() 是标头,object.values 是匹配数据。

所以,我认为这可能有效(可能需要调试)

<table id = "myTable" class ="table table-bordered">
    {% for item in qs %}
      {% if forloop.first %}
         <thead class = "alert-warning"> 
         <tr>
           {% for name in item.keys %} <th>{{name}}</th> {% endfor %}
         </tr>
         </thead>

         <tbody>
      {% endif %}

      <!-- still in the outer loop iterating over qs -->
      <tr> 
        {% for value in item.values %}
           <td {% if forloop.first %}contenteditable='true'{%endif%} >{{value}}</td>
        {% endfor %}
     </tr>
    {% endfor %}
</tbody>
</table>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    • 2015-10-26
    • 2016-05-05
    • 2020-08-11
    相关资源
    最近更新 更多