django 1.7 模板路径设置

目的:通过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的内容

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值