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

本文介绍了在Django项目中如何配置并加载模板文件夹,提供了三种不同的视图方法来展示模板内容,并演示了如何通过Context传递数据到模板。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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))

 

转载于:https://www.cnblogs.com/whzym111/p/5888602.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值