django中模板的认识
一、django中settings.py配置html模板路径的方式
1、直接在
TEMPLATES中配置相对路径'DIRS': ['templates'] # 需要在项目下创建一个templates文件夹2、在
TEMPLATES中配置绝对路径(不推荐使用)'DIRS': ['/Users/shuiping.kuang/Documents/aaron/python/django-web/demo01/templates']3、使用
os模块'DIRS': [os.path.join(BASE_DIR,'templates' )]4、上面三种方式推介指数 3 > 1 > 2
二、模板的渲染
1、使用创建
app默认使用的render渲染模板def index(request): return render(request, 'index.html')class Home(View): def dispatch(self, request, *args, **kwargs): print(request.method) return super(Home, self).dispatch(request, *args, **kwargs) def get(self, request): print(request.GET) return render(request, 'index.html') def post(self, request): pass2、使用
render_to_response渲染模板from django.shortcuts import render, render_to_response def index(request): return render_to_response('index.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('index.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)5、总结:虽然有很多种渲染模板的方式,但是还是选用官方推荐使用的
render方法来渲染
三、在自己创建的app下面创建templates专属当前app使用(模板分发,类似前面讲的路由分发一样的)
- 1、创建的
app必须先注册 - 2、在
settings.py配置文件中配置'APP_DIRS': True,(默认就是True),相当是不需要配置 - 3、在
app中创建一个文件夹templates - 4、跟上面一样的使用了
- 5、说明当组件中模板名字和全局模板名字一样的会使用全局的模板,其中模板查找顺序:全局-->
app模板(当前views.py可以查找到别的app中的templates模板)
四、静态文件的配置
在开发过程中可能会使用到的
css文件、js文件、img文件我们统一归到静态文件中
1、加载静态的也是一个
app,查看app中是否加载该组件INSTALLED_APPS = [ ... 'django.contrib.staticfiles', ]2、静态文件有两种方式(类似前面说的路由分发一样的)
- 1.全局的静态文件(根目录下创建一个
static的文件夹) - 2.局部的静态文件(组件中创建一个
static的文件夹)
- 1.全局的静态文件(根目录下创建一个
3、说明(静态文件夹的命名是根据
setting.py中STATIC_URL一样就可以)STATIC_URL = '/static/'4、在
settings.py中配置静态文件地址STATICFILES_DIRS = ( 'static', )5、在模板中使用静态文件参考博客,这在
gitbook上写load就会直接报错