Linux下开发python django程序(模板设置和载入数据)

1.添加templates文件夹

2.修改settings.py文件

import os #引用 os模块

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  #添加BASE_DIR路径

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(BASE_DIR,  '\\csvt03\\templates').replace('\\','/'),
    'app1',
) #在TEMPLATE_DIRS节点中设置模板文件夹路径

 

2.views 3种方式 载入模板

from django.http import HttpResponse
from django.template import loader,Context,Template
from django.shortcuts import render_to_response
def index(req):
        t=loader.get_template('index.html')
        c = Context({})
        return HttpResponse(t.render(c))

def index1(req):
        user={'name':'wanghao','age':32,'addr':'cq','sex':'Fmale'}
        return render_to_response('index.html',{'user':user})

def index2(req):
        t= Template('<h1>hello {{user.name}}</h1><br><hl>age:{{user.age}}</hl><br><hl>address:{{user.addr}}</hl><br> <hl>sex:{{user.sex}}</hl>')
        user={'name':'wuxi','age':31,'addr':'cq','sex':'male'}
        c=Context({'user':user})
        return HttpResponse(t.render(c))

 

posted @ 2016-09-20 14:03  whzym111  阅读(297)  评论(0编辑  收藏  举报