I'm trying to learning django templates but it's not easy.
I have a certain views.py containing a dictionary to be rendered with a template. The dictionary is made of key-value pairs, where key are unique names and values are some values associated to those names. I render the dictionary in the following way:

return render_to_response('results.html', {'data': results_dict})

Now my problem is that in my template I need to display the names in alphabetical (or ASCIIbetical) order with the relatives values.
Actually in my template I have:

<table>
{% for key, value in data.items %}
    <tr>
        <td> {{ key }}: </td> <td> {{ value }} </td>
    </tr>
</table>

如何以排序方式呈现数据?

推荐答案

在views.py(Python2)中:

return render_to_response('results.html',
    {'data': sorted(results_dict.iteritems())})

或在views.py(Python3)中:

return render_to_response('results.html',
    {'data': sorted(results_dict.items())})

在模板文件中:

{% for key, value in data.items() %}
    <tr>
        <td> {{ key }}: </td> <td> {{ value }} </td>
    </tr>
{% endfor %}

Django相关问答推荐

如何在Django模型mixin字段定义中引用模型名称?

在保存新实例之前删除一个实例(Django模型保存方法)

其中实际的数据库提取在DRF list()中完成

如何在Django上创建ManyToMany管理面板?

Django:作为模型中的列表元素的字段

表单集中的每个表单验证

当我告诉它时,如何使用 Django 的记录器来记录回溯?

如何缓存 Django Rest Framework API 调用?

Django 基于角色的视图?

如何在 Django 模板上实现 back链接?

如何获取 Django 模型来自的应用程序?

django npm 和 node 包架构

Django:在模型管理器中获取模型的表名?

在 django admin 中链接到外键对象

Django Admin:如何在内联中显示模型上定义的属性?

Django unique_together 与可为空的 ForeignKey

django select_related - 何时使用它

django.urls.path中name参数的作用是什么?

如何检测 Heroku 的环境?

Django: Force强制 Select 相关?