我正在使用Django 1.11,Apache 2.2和mod_wsgi创建一个使用Python 2.7的Web应用程序。我在渲染页面时遇到问题。 完整的追溯,
Environment:
Request Method: GET
Request URL: http://website.com/~user/irtf/
Django Version: 1.11.1
Python Version: 2.7.13
Installed Applications:
['irtf.apps.IrtfConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mod_wsgi.server']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/home/path/irtf_website/mysiteenv/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/home/path/irtf_website/mysiteenv/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/home/path/irtf_website/mysiteenv/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/path/irtf_website/mysite/irtf/views.py" in index
18. return HttpResponse(template.render(request))
File "/home/path/irtf_website/mysiteenv/lib/python2.7/site-packages/django/template/backends/django.py" in render
64. context = make_context(context, request, autoescape=self.backend.engine.autoescape)
File "/home/path/irtf_website/mysiteenv/lib/python2.7/site-packages/django/template/context.py" in make_context
287. raise TypeError('context must be a dict rather than %s.' % context.__class__.__name__)
Exception Type: TypeError at /irtf/
Exception Value: context must be a dict rather than WSGIRequest.
我的 views.py 是,
def index(request):
template = loader.get_template('irtf/index.html')
return HttpResponse(template.render(request))
可能无关紧要,但此页面的模板只包含文字和链接。
答案 0 :(得分:10)
这是因为第一个parameter应该是字典。你可能把它与渲染捷径混在一起
template = loader.get_template('irtf/index.html')
return HttpResponse( template.render({}, request))
使用render shortcut代替
return render(request,'irtf/index.html')