我该如何满足 direct_to_template 的导入?

23 投票
2 回答
14582 浏览
提问于 2025-04-17 20:14

我在一个最初是用Pinax 0.7做的项目中遇到了一个错误页面:

ImportError at /
No module named simple
Request Method: GET
Request URL:    http://stornge.com:8000/
Django Version: 1.5
Exception Type: ImportError
Exception Value:    
No module named simple
Exception Location: /home/jonathan/clay/../clay/urls.py in <module>, line 3
Python Executable:  /home/jonathan/virtual_environment/bin/python
Python Version: 2.7.3
Python Path:    
['/home/jonathan/clay/apps',
 '/home/jonathan/virtual_environment/local/lib/python2.7/site-packages/pinax/apps',
 '/home/jonathan/clay',
 '/home/jonathan/virtual_environment/local/lib/python2.7/site-packages/distribute-0.6.24-py2.7.egg',
 '/home/jonathan/virtual_environment/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg',
 '/home/jonathan/virtual_environment/lib/python2.7',
 '/home/jonathan/virtual_environment/lib/python2.7/plat-linux2',
 '/home/jonathan/virtual_environment/lib/python2.7/lib-tk',
 '/home/jonathan/virtual_environment/lib/python2.7/lib-old',
 '/home/jonathan/virtual_environment/lib/python2.7/lib-dynload',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-linux2',
 '/usr/lib/python2.7/lib-tk',
 '/home/jonathan/virtual_environment/local/lib/python2.7/site-packages',
 '/home/jonathan/virtual_environment/local/lib/python2.7/site-packages/PIL']
Server time:    Mon, 25 Mar 2013 13:16:33 -0400

它在urls.py的第3行出问题了,具体是:

from django.views.generic.simple import direct_to_template

我该如何更改导入的内容或者它使用的地方呢:

    urlpatterns = patterns('',
    url(r'^$', direct_to_template, {
        "template": "homepage.html",
    }, name="home"),

看起来我可以创建一个视图,使用render_to_response()来处理主页,但我想知道应该怎么解决这个问题,如果没有人告诉我更好的方法,我就先用这个办法。

2 个回答

2

除了基于类的视图 TemplateView,你还可以像这样使用 render 函数:

from django.shortcuts import render

urlpatterns = patterns("",
    url(r'^$', lambda request: render(request, 'homepage.html'), name="home"),
)
54

direct_to_template这个功能已经不再推荐使用了。在django 1.5版本中,建议你使用一种基于类的视图,叫做 TemplateView,你可以在 urls.py 文件中使用它。

from django.views.generic import TemplateView

urlpatterns = patterns('',
    url(r'^$', TemplateView.as_view(template_name='homepage.html'), name="home"),
)

关于如何迁移到1.4版本(这个功能在那时就不推荐了)的信息,可以在 这里 找到。

撰写回答