Django-设置url.py和views.py

2024-04-25 22:08:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Django的新手,正在尝试配置url.py和views.py文档。这可能是一个非常简单的问题,但我无法设置url.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

My 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

Tags: 文件djangofrom文档pyimporturlindex
2条回答

除了在settings.py中设置TEMPLATE_DIRS之外:

import os

ROOT_PATH = os.path.dirname(__file__)

TEMPLATE_DIRS = (    
    os.path.join(ROOT_PATH, 'templates'),
)

mysite/url.py

urlpatterns = patterns('',
    url(r'^$', include('app.urls', namespace='app'), name='app'),
)

app/url.py

urlpatterns = patterns('app.views',
    url(r'^$', 'index', name='index'),
)

views.py代码中,按原样将templates/index.html更改为index.html,模板应位于:

mysite/mysite/templates/index.html

另一方面,您的cssjsimg文件夹最好放在其他地方,比如mysite/static文件夹。

是否在TEMPLATE_DIRS中定义了模板路径。

设置.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

然后不要这样做。这应该管用。

您的目录结构应该是:

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

相关问题 更多 >