一、django
中配置html
模板路径的方式有
都是在项目文件的
settings.py
中配置
1、使用相对路径(常用)
'DIRS': ['templates']
2、使用绝对路径
'DIRS': ['F:/workTest/python/django/firstproject/templates'],
3、使用
OS
模块查找路径(使用pycharm
创建django
项目就是这个)'DIRS': [os.path.join(BASE_DIR,'templates' )],
二、渲染模板的方式
1、直接使用
render
渲染(常用且安全方式)[默认导包]def index1(request): return render(request,'book1.html')
2、使用
render_to_response
渲染模版[需要导入包]from django.shortcuts import render,render_to_response def index3(request): return render_to_response('book.html')
3、使用
render_to_string
渲染模版[需要导包]from django.http import HttpResponse from django.template.loader import render_to_string def index4(request): html = render_to_string('book1.html') return HttpResponse(html)
4、
使用get_template
渲染模版[需要导包]from django.http import HttpResponse from django.template.loader import get_template,render_to_string def index5(request): t = get_template('book.html') html = t.render({}) return HttpResponse(html)
三、在自己创建的组件(app
)下创建一个templates
文件夹存放当前组件下的模块
- 1、
settings.py
文件夹下的设置'APP_DIRS': True,
(默认就是true
) 2、在
settings.py
中添加自己创建的组件(app
)INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'book' ]
3、在组件下创建
templates
文件夹- 4、渲染方式跟上面一样的
总结一般我们模版文件不会放在组件(
app
)里面,如果放在里面就不需要配置'DIRS': ['templates']