我是 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
最佳答案
除了在 settings.py
中设置您的 TEMPLATE_DIRS
之外:
import os
ROOT_PATH = os.path.dirname(__file__)
TEMPLATE_DIRS = (
os.path.join(ROOT_PATH, 'templates'),
)
我的网站/urls.py
urlpatterns = patterns('',
url(r'^$', include('app.urls', namespace='app'), name='app'),
)
应用程序/urls.py
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
文件夹。
关于python - Django - 设置 urls.py 和 views.py,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14012340/