将附加数据传递给Django中的模板 [英] Passing additional data to a template in Django

查看:232
本文介绍了将附加数据传递给Django中的模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次我使用Django编写代码时,我面对同样的问题(我认为这是因为我缺乏使用这个框架的经验):

Every time I code something using Django, I am faced to the same issue (I think this is due to my lack of experience using this framework):

知道如何传递我从查询集到模板以及如何显示它的参数,但是我不知道如何添加视图中计算的参数,并在模板中使用它们。

I know how to pass arguments I had from a queryset to a template and how to display it but I don't know how to add argument computed in the view and use them in the template.

简单视图(我掌握它):
示例:检索比萨饼列表,并在模板中显示

views.py

Pizzas = Pizza.objects.all()
return render_to_response( "pizza.html" , {'pizzas':Pizzas} )

pizza.html

{% for pizza in pizzas %}
    <li>pizza.name</li>
{% endfor %}

但是,我们想添加一些链接的参数查询器,但不在数据库中,就像我在视图中计算的东西一样,我不知道如何将这个参数传递给模板以及如何使用它 - > 编辑:我想订购我所有的比萨饼

But, let's say I want to add some arguments linked to the queryset but which are not in the database like something I computed in the view, I don't know how to pass this argument to the template and how to use it -> EDIT : I want to order all my pizza by total calories in the template.

示例:对于每个比萨饼,我已经计算了卡路里的数量

views.py

Pizzas = Pizza.objects.all()
tab = []
for pizza in Pizzas:
    # Compute some data and return the total number of calories for one pizza
    total_number_calories = XXX
    tab.append({'p':pizza,'calories':total_number_calories'})        
return render_to_response( "pizza.html" , {'pizzas_calories':tab} )

pizza.html

?

我甚至不确定我将这些附加数据传递给模板的方法是很好的(创建一个表并将其作为参数传递给模板。

I am not even sure my way to pass these additional data to the template is good (creating a table and pass it as an argument to the template.

如果您在Django中有任何想法或最佳做法,我会接受(很多人使用Django将执行相同的操作!)

If you have any idea or best practices to do that in Django I'll take it (and lot of people using Django will do the same !)

推荐答案

您应该始终尽可能在视图中尽可能多地使用代码,显示,总共卡路里的排序只是for循环后一个额外的行:

You should always try and do as much as possible in the view. With the code you've shown, ordering by total calories is just one extra line after the for loop:

tab.sort(key=lambda t: t['calories'])

这篇关于将附加数据传递给Django中的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆