【问题标题】:Passing Dictionary from Views to Template将字典从视图传递到模板
【发布时间】:2018-03-23 17:12:36
【问题描述】:

首先,我查看了许多其他资源以尝试获得帮助,但我觉得我基本上拥有他们所拥有的东西,但它对我不起作用。

所以我有这个作为我的观点:

class MVS(ListView):
    model = VTSI
    template_name = "templates/mvs.html"
    def index(request):
        q = VTSI._meta.get_fields()
        d = {}
        for x in q:
            z = x.verbose_name
            d.update({z:z})
        return render(request, 'mvs', {'d': d})

简单来说,上面的类试图获取模型文件中的所有列名并获取它们的详细名称。然后它将获取这些冗长的名称,将其放入字典中,然后将其传递给模板以显示所有这些列名。我之前尝试过传递一个列表,但我了解到需要字典才能将值传递给模板。

这就是我的模板:

{% extends "base.html" %}
{% load crispy_forms_tags %}
{% load staticfiles %}
{% block content %}
<div class="row">
  <div class="col-sm-3">
    <h2>Description of Table</h2>
  </div>
</div>
<table id="listview" class='table table-striped table-bordered'>
<thead>
<tr>
  <th>Column One</th>
  <th>Column Two</th>
</tr>
</thead>
<tbody>
{% for v in d.items %}
<tr>
<td> {{ v }}</td>
<td> </td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}

此模板为空白,不显示任何列名。我错过了什么,我该如何解决这个问题?

【问题讨论】:

  • 永远不会调用您的索引方法。
  • 如何以及在哪里调用它?
  • 你不会的。这不是你编写基于类的视图的方式。
  • 因此,如果我要将 index 方法移到类之外,将所有内容分开,然后在类中编写如下内容:index(request)。这会是前进的最佳方法吗? I was referencing the Django Docs.

标签: django python-2.7 django-templates django-views


【解决方案1】:

查看使用ListView的文档

试着改变你的代码看起来更像

class MVS(ListView):
    model = VTSI
    template_name = "templates/mvs.html"
    def get_context_data(self, **kwargs):
        q = VTSI._meta.get_fields()
        d = {}
        for x in q:
            z = x.verbose_name
            d.update({z:z})
        return d

【讨论】:

  • 所以我正在浏览 ListView 并使用了您上面列出的内容。然而,在我的模板中,我仍然对如何在字典中显示对象感到困惑。我有它:{% for v in object_list %} {{ v }} {{ v.v }}{ % endfor %} 2 v 的目的是查看它是否会以任何一种方式显示,但两种方式都不起作用。那么我的模板会是什么样子?
【解决方案2】:

所以我在上面的 user6731765 的帮助下找到了自己问题的答案,我所做的是:

class MVS(ListView):
model = VTSI
template_name = "templates/mvs.html"    
def get_context_data(self, **kwargs):
    context = super(MVS, self).get_context_data(**kwargs)
    context['v'] = VTSI._meta.get_fields()        
    return context

然后在我的模板中,我这样做了:

{% for a in v %}
<tr>
  <td> {{ a.verbose_name }}</td>
  {% empty %} 
    <td> Sorry, empty </td>
  <td> </td>
</tr>
{% endfor %}

编辑:对于未来的读者,所有这一切的重点是 dictionary_value['something_here'] 部分。出于某种原因,我无法准确解释,您需要将其添加到字典变量中,然后您将遍历模板中的“something_here”部分。你可以在其他方法中做任何你想做的事情,然后通过这样做来调用它:

dictionary_variable['something_here'] = self.some_other_method()
return dictionary_variable

在模板中,您将再次遍历“something_here”部分以显示任何内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-07
    • 1970-01-01
    • 2015-09-18
    • 2015-07-07
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 2017-04-26
    相关资源
    最近更新 更多