目的:通过127.0.0.1/blog/index访问模板的中的index.html文件
1,创建Django项目
fage@iZ94s1sibj6Z:~/python$ django-admin.py startproject website
会生成一个website的工程目录,工程目录在有manage.py和一个同名的website目录
fage@iZ94s1sibj6Z:~/python$ cd website/
fage@iZ94s1sibj6Z:~/python/website$ ls -l
total 8
-rwxr-xr-x 1 fage fage 250 Nov 9 21:36 manage.py
drwxrwxr-x 2 fage fage 4096 Nov 9 21:36 website
2,在工程目录website下创建blog的app
fage@iZ94s1sibj6Z:~/python/website$ django-admin.py startapp blog
fage@iZ94s1sibj6Z:~/python/website$ ls -l
total 12
drwxrwxr-x 3 fage fage 4096 Nov 9 21:43 blog
-rwxr-xr-x 1 fage fage 250 Nov 9 21:36 manage.py
drwxrwxr-x 2 fage fage 4096 Nov 9 21:36 website
3,修改同名website目录的中urls.py,内容如下
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'web1.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^blog/index/$', 'blog.views.index'),
)
~
4,修改同名website目录中setting.py,添加app和设置模板路径
将blog应用添加进去
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
)
在setting.py的最后设置模板路径
from os.path import join
TEMPLATE_DIRS = (
join(BASE_DIR, 'templates'),
)
第四步的解释来自http://stackoverflow.com/questions/20353880/template-dirs-is-missing-in-settings-py-django-1-6
Use the below given code snippet. Paste it in last of the settings.py file.
from os.path import join
TEMPLATE_DIRS = (
join(BASE_DIR, 'templates'),
)
Here BASE_DIR means your project directory, not the inner directory where the settings.py resides. Create a directory named "templates" (without quotes) inside the BASE_DIR and store your templates inside that directory. Django will join templates directory to the BASE_DIR using os.path.join() function. Hope this helps.
5,修改blog/view.py,内容如下
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader,Context
# Create your views here.
def index(req):
t = loader.get_template('index.html') # auto load file 'index.html' from dir templates
c = Context({})
return HttpResponse(t.render(c))
6,在工程目录website下新建templates目录,进入temlates,编辑index.html,
最后runserver,访问127.0.0.1:8000/blog/index/,就会读取temlates/index.html的内容