尽管我已经使用自定义过滤器通过变量键访问字典的值,但我无法这样做。以下是代码片段。无法使用Django模板中的过滤器使用变量键访问上下文字典值
view.py
def DBConnect(request):
c = {}
c['dbs'] = get_all_db() #returns an array of db.
for db in c['dbs']:
c[db] = get_all_tables(db) #returns all the tables in db and storing in context dictionary with db name as key.
return render_to_response('test.html', c)
作为一个实施例C将包含如下: C = { 'DBS':[u'db1' ,u'db2 '],u'db1':[U” TB1' ,u'tb2 '],u'db2':[u'tb21' ,u'tb22' ]}
app_filter.py
@filter.filter
def get_item(dictionary, key):
return dictionary.get(key)
的test.html .... 。 ...
{%for db in dbs%}
do something with {{db}} <- this is fine, I am getting all the dbs here.
{{ c | get_item : db }} <- This code is not working, If I directly pass dbname literal than it is working fine.
{% endfor %}
请建议我是否应以不同的方式通过上下文来解决此问题。 在此先感谢。
你通过“星展银行”到测试模板?根据上面的代码,您传递的是'c',它是'dbs'作为其中一个关键字的字典。 –
谢谢Rohan和AKS的回复。我对Django框架相当陌生。我将实施这些解决方案并将标记为答案。我非常确定这两种解决方案都可以完成这项工作。谢谢AKS的解释,这真的有助于我理解与Django相关的一些事情。再次感谢你们。 +1为你们俩。:-) – Amit
@Amit:感谢您的评论,我们很乐意提供帮助。还请阅读[当某人回答我的问题时该怎么办?](http://stackoverflow.com/help/someone-answers)。 – AKS