python - 在 Django 模板中显示字典值

标签 python django templates

全部,

我的 views.py 中有以下内容

def getgradeform(request):
   id1=request.user.get_pf().id
   sc=Sc.objects.filter(id=id1)
   logging.debug(sc)
   logging.debug("++++")
   dict={}
   dict.update({'sc': sc})
   return render_to_response('content/add.html',dict)

Logging.debug 的输出为 [<sc: Robert>]

我的问题是如何在模板中显示 Robert。

我在模板中尝试了以下内容:<input type ="text" value={{sc}}/> //This gives me the dictionary itself

<input type ="text" value={{dict.sc}}/> //This also doesnt work.

谢谢......

最佳答案

如果你想要字典中的任何值,你必须在途中这样做

dict.key

(在 python 上你会把它写成 dict['key'])

因此,要显示使用键“name”存储的值

{{ sc.name }}

无论如何,我认为这不是你的情况。我认为您看到的不是字典,而是从模型定义的对象(就像数据库中的条目一样)。 您存储在 dict (不要将该值称为 dict ,您正在屏蔽关键字)具有值变量 sc 的键“sc” ,这是从模型返回的。我不得不猜测,因为我不知道这个模型是怎样的。也许“罗伯特”存储在属性 name 中, id或类似的东西?

然后您需要显示适当的属性,例如

{{ sc.name }}
{{ sc.id }}

关于python - 在 Django 模板中显示字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2152652/

相关文章:

python - 值错误 : '10.0.0.0/24' does not appear to be an IPv4 or IPv6 network

python - gekko中的一维飞机飞行最优控制问题

python - 如何允许用户在 Django Rest Framework 中仅修改他的数据

python - 我的 Django 应用程序可以充当 header 剥离代理吗?

c++ - 在嵌套名称说明符中使用 simple-template-id 是否明确表示类模板特化?

python - 在 Rstudio 中安装 Python 模块

python - TurnkeyLinux Django 安装。默认管理员密码?

c++ - c++ std::function 如何绑定(bind)到模板函数?

c++ - 在 C++ 的子类中强制执行静态方法重载

python - 正则表达式匹配内部 '.'