V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
34D
V2EX  ›  Python

Django 1.7 模板路径问题

  •  
  •   34D · Oct 24, 2014 · 5577 views
    This topic created in 4213 days ago, the information mentioned may be changed or developed.

    这几天在看Django,今天碰到了一个模板的路径问题。首先我的文件结构是这样的

    /mysite
    /mysite
    view.py
    settings.py
    urls.py

    /templates
    index.html
    db.sqlite3
    manage.py

    view里的代码如下

    def test(request):
    html = open(“index.html”).read()
    return HttpResponse(html, content_type=“text/html”)

    但是出现了错误,说找不到index文件。于是google之,说在settings.py重加入

    TEMPLATEDIRS = (
    os.path.join(os.path.dirname(
    file_), 'templates').replace('\','/'),
    )
    能解决。果断加上,调试,不行。而且网上也有人说1.6之后不用手动设置TEMPLATE_DIRS,求大神解救,已经困扰我一下午了。T_T

    5 replies    2014-11-10 18:33:09 +08:00
    34D
        1
    34D  
    OP
       Oct 24, 2014
    我靠,怎么是这幅样子。
    哭了。
    valuedlute
        2
    valuedlute  
       Oct 24, 2014
    用tree命令打出来...

    我的是
    import os
    BASE_DIR = os.path.dirname(os.path.dirname(__file__))

    TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
    wangyongbo
        3
    wangyongbo  
       Oct 28, 2014 via iPhone   ❤️ 1
    我觉得你这个不是因为模版路径的问题,你用的open去打开文件,他会在你这整个项目的根目录找这个文件。你可以Open换成render_to_string
    34D
        4
    34D  
    OP
       Oct 28, 2014
    @wangyongbo 对的,我后来用render_to_reponse了。
    NearTan
        5
    NearTan  
       Nov 10, 2014
    根据最新的(1.7)官方文档 若 app 名字为 polls
    默认路径为 polls/templates/polls/index.html
    附连接 https://docs.djangoproject.com/en/1.7/intro/tutorial03/
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4264 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 00:56 · PVG 08:56 · LAX 17:56 · JFK 20:56
    ♥ Do have faith in what you're doing.