对DJango视图(views)和模版(templates)的使用详解
视图
在django中,视图对WEB请求进行回应
视图接收reqeust对象作为第一个参数,包含了请求的信息
视图就是一个Python函数,被定义在views.py中
定义完成视图后,需要配置urlconf,否则无法处理请求
在Django中,定义URLconf包括正则表达式、视图两部分
Django使用正则表达式匹配请求的URL,一旦匹配成功,则调用应用的视图
注意:只匹配路径部分,即除去域名、参数后的字符串
在test1/urls.py插入booktest,使主urlconf连接到booktest.urls模块
视图代码
#views.py #一个简单的视图,固定返回hrlloworld defindex(request): returnHttpResponse('helloworld')
模板
模板是html页面,可以根据视图中传递的数据填充值
模板和应用booktest是同级目录
模板的结构templates/应用名(booktest)/*.html
将模板的地址信息拼接在settings.py文件中的TEMPLATES的DIRS值中:'DIRS':[os.path.join(BASE_DIR,‘templates')],
urls代码
方式一:直接修改原始的urls
#fanlie/fanlei/urls.py fromdjango.conf.urlsimportinclude,url fromdjango.contribimportadmin frombooktestimportviews urlpatterns=[ url(r'^admin/',include(admin.site.urls)), #如果匹配的是空就就调用views.index返回首页 url(r'^$',views.index), ]
方式二:在应用目录下修改
#fanlie/fanlei/urls.py urlpatterns=[ url(r'^admin/',include(admin.site.urls)), #什么都不干直接去booktest.urls去找相应的匹配 url(r'^',include('booktest.urls')), ] #fanlei/booktest/urls.py fromdjango.conf.urlsimporturl from.importviews urlpatterns=[ #js结尾就是调用视图中的函数js url(r'.*.js',views.js), #直接访问代表是首页,调用视图中的函数index url(r'^$',views.index), #如果是image开头的代表是图片,直接让DJango去打开对应的图片返回 url(r'^images/(?P.*)','django.views.static.serve',{'document_root':'/home/python/Desktop/fanlei/templates/booktest/images'}), ]
上面模板用到的视图
fromdjango.shortcutsimportrender defindex(request): #返回引号中的文件的内容 returnrender(request,'booktest/index.html') defjs(request): #返回引号中的文件的内容 returnrender(request,'booktest/jquery-1.12.4.js')
以上这篇对DJango视图(views)和模版(templates)的使用详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。