我是Django的新手,正在尝试配置我的urls.py和views.py文档。这可能是一个非常简单的问题,但我不能为我的生活设置我的urls.py和views.py文档,以便localhost / index指向我创建的index.html文件。我已经按照Django项目教程来写了这封信并试了很多很多变种,但这并不是为了点击我。任何帮助将不胜感激!
index.html文件位于mysite / templates / index.html
我的文件夹结构是这样的......
mysite/
mysite/
__init__.py
settings.py
urls.py
wsgi.py
app/
__init__.py
admin.py
models.py
tests.py
urls.py
views.py
templates/
css
img
js
index.html
我的views.py包含:
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import Context, loader
from django.http import Http404
def index(request):
return render(request, "templates/index.html")
更新:我的文件夹结构现在如下所示:
mysite/
mysite/
__init__.py
settings.py
urls.py
wsgi.py
templates/
index.html
app/
__init__.py
admin.py
models.py
tests.py
urls.py
views.py
static/
css
img
js
答案 0 :(得分:3)
除了在TEMPLATE_DIRS
中设置settings.py
之外:
import os
ROOT_PATH = os.path.dirname(__file__)
TEMPLATE_DIRS = (
os.path.join(ROOT_PATH, 'templates'),
)
urlpatterns = patterns('',
url(r'^$', include('app.urls', namespace='app'), name='app'),
)
urlpatterns = patterns('app.views',
url(r'^$', 'index', name='index'),
)
在您的views.py
代码中,将templates/index.html
更改为index.html
,模板应位于:
mysite/mysite/templates/index.html
另外请注意,您的css
,js
和img
文件夹最好放在其他地方,例如mysite/static
文件夹。
答案 1 :(得分:2)
您是否在TEMPLATE_DIRS
中定义了模板路径。
settings.py
# at start add this
import os, sys
abspath = lambda *p: os.path.abspath(os.path.join(*p))
PROJECT_ROOT = abspath(os.path.dirname(__file__))
sys.path.insert(0, PROJECT_ROOT)
TEMPLATE_DIRS = (
abspath(PROJECT_ROOT, 'templates'), # this will point to mysite/mysite/templates
)
然后将模板文件夹移至mysite > mysite > templates
然后只需return render(request, "templates/index.html")
而不是return render(request, "index.html")
。这应该有用。
您的目录结构应为:
mysite/
mysite/
__init__.py
settings.py
urls.py
wsgi.py
templates/
index.html
static/
css/
js/
app/
__init__.py
admin.py
models.py
tests.py
urls.py
views.py