如何在django应用程序中将Dictionary值从视图传递到模板

时间:2017-03-20 06:05:19

标签: python django python-2.7 dictionary

我只是想学习一个django项目。我已经使用django命令创建了项目和内部项目myapp 在 / myproject / myapp $ 目录中,我有views.py文件。另一个目录 / myproject / myapp / templates $ 我有hello.html文件。我想使用render函数将来自views.py文件的Dictionary值发送到hello.html文件。但我收到了一些名为

的错误
**Internal Server Error: /hello/
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 42, in inner
    response = get_response(request)
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/joy/pythonWork/myproject/myapp/views.py", line 8, in hello
    name     : 'xyz',
NameError: global name 'name' is not defined**

我没有任何想法,如何解决这个问题。有人请帮助我。 我的文件列在下面:

/views.py

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

def hello(request):
   personalDetails = {
       name     : 'xyz',
       phoneno  : '722924374'
   }
   return render(request, "hello.html", {personalDetails})

/hello.html

<html>
<body>

<h1>Hello</h1>{{personalDetails}}

</body>
</html>

4 个答案:

答案 0 :(得分:1)

你传递字典。字典键应该是字符串。

def hello(request):
   personal_details = {
       'name': 'xyz',
       'phoneno': '7022924374',
   }
   return render(request, 'hello.html', {'personal_details': personal_details})

答案 1 :(得分:0)

你应该像这样使用render

return render(request, "hello.html", {"personalDetails": personalDetails})

答案 2 :(得分:0)

尝试此更改

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

def hello(request):
   personalDetails = {
       name     : 'xyz',
       phoneno  : '722924374'
   }
   return render(request, "hello.html", **personalDetails)

并在你的HTML中

<html>
<body>

<h1>Hello</h1>{{name}}

</body>
</html>

答案 3 :(得分:0)

def hello(request):
   personalDetails = {
       name     : 'xyz',
       phoneno  : '7022924374'
   }
   return render(request, "hello.html", {"personalDetails":personalDetails})

在模板中:

<html>
<body>
{% for item in personalDetails %}
   <h1>Hello</h1>{{item.name}}
{% endfor %}

</body>
</html>