在django模板中显示字典值

Hul*_*ulk 1 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)
Run Code Online (Sandbox Code Playgroud)

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.

谢谢......

Khe*_*ben 6

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

dict.key
Run Code Online (Sandbox Code Playgroud)

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

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

{{ sc.name }}
Run Code Online (Sandbox Code Playgroud)

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

你需要显示适当的属性,比如

{{ sc.name }}
{{ sc.id }}
Run Code Online (Sandbox Code Playgroud)