Skip to main content
 首页 » 编程设计

python之在 Django 模板中使用 with 和 add 组合变量失败

2025年05月04日37dudu

我在使用 with 和 add 组合 Django 模板中的变量时遇到了一些问题。

这是我传递给模板的变量

year = 2015 
source = u'temp_dir' 

在我的模板中,with 在下面,但 temp 仍然返回空。

{% with temp="home/"|add:source|add:"/"|add:year %} 
{{temp}} 
{% withend %} 

当我从 temp 中删除 year 时,temp 值变为 home/temp_dir/ (这是正确的)

{% with temp="home/"|add:source|add:"/"%} 
{{temp}} 
{% withend %} 

我也尝试过将 year 转换为 unicode

year = u'2015' 
source = u'temp_dir' 

但它仍然是空的,似乎 year 有问题。

更新 2015/09/02

这是我的看法:

## I will get a list of dicts from the db then do.. 
for result in results: 
    result.year = unicode(result.year) 
 
return results 

回答

当从数据库查询时,它返回一个 QuerySet 对象,它不允许我的程序将新键插入到 QuerySet 对象中的每个字典中。但是当我将它们复制到另一个字典列表中时,我可以向其中添加新键。

旧代码:

## I will get a list of dicts from the db then do.. 
for result in results: 
    result.year = unicode(result.year) 
 
passed_dict['results'] = results 
return  render_to_response(index.html, passed_dict) 

新代码:

final_results = [] 
for result in results: 
    temp_result = result 
    temp_result.year = unicode(result.year) 
    final_results.append(temp_result) 
 
passed_dict['results'] = final_results 
return  render_to_response(index.html, passed_dict) 

请您参考如下方法:

您正试图在上下文中将 year 作为整数传递。 您需要在上下文中将 year 的值作为字符串传递。

你需要改变

year = 2015 # passing integer value is wrong here 

到

year = '2015' # pass year in string 

add在您的情况下,内置模板过滤器需要两个值都是字符串或整数才能正确执行加法。

This filter will first try to coerce both values to integers. If this fails, it’ll attempt to add the values together anyway. This will work on some data types (strings, list, etc.) and fail on others. If it fails, the result will be an empty string.

在这里,您将一个值作为字符串传递,将另一个值作为整数传递,这导致显示空字符串。