一、Template#
1、 Template初探##
到目前为止我们只是简单的将后端数据显示到页面上,没有涉及到HTML代码,而优雅的网站总是通过CSS+HTML,甚至还有强大的JS的支持
在这个教程中要打造一个Blog,所以我们设置一个Blog界面,原本打算使用Bootstrap作为前段的工具, 不过经过其他人的建议, 使用了更加轻量级的Pure,同样是响应式页面设置,这也将是未来的主流吧
在my_blog下添加文件名,文件夹名为templates
1.7/1.8版本Django已经修改的template添加形式
在my_blog/my_blog/settings.py下设置templates的位置
意思是告知项目templates文件夹在项目根目录下
##2、 第一个template##
template/test.html 简单写一个 template html文件
其中{{ current_time }}是Django Template中变量的表示方式
在article/views.py中添加一个函数逻辑
然后设置对应的url在my_blog/my_blog/urls.py下
重新启动服务器 python mange.py runserver localhost:9000 然后在浏览器输入 http://localhost:9000/test/,可以看到
##3、 正式编写template##
在template文件夹下增加base.html,并在其中增加如下代码
上面这段html编写的页面是一个模板,其中{% block content %} {% endblock %}字段用来被其他继承这个基类模板进行重写
我们继续在templates文件夹下添加home.html文件
其中
{% for <element> in <list> %}与{% endfor %}成对存在,这是template中提供的for循环tag
{% if <element> %} {% else %} {% endif %} 是template中提供的if语句tag
template中还提供了一些过滤器
然后修改my_blog/article/views.py,并删除test.html
修改my_blog/my_blog/urls.py
现在重新打开http://localhost:9000/,发现Blog的整理框架已经基本完成,到现在我们已经了解了一些Django的基本知识,搭建了简单的Blog框架,剩下的就是给Blog添加功能
查看当前整个程序的目录结构
##4、 将代码上传到Github##
在github中新建仓库Django-blog,填写简单的描述
查看当前目录位置
在项目的根目录下初始化git
在添加远程github
在根目录下增加’.gitignore’和’LICENSE’和’README.md ’文件
添加所有文件
查看当前状态
commit操作
发现没有设置用户名和邮箱,进行设置
重新commit操作
上传github
发现出错,使用git pull –rebase origin master命令
重新上传github
上github网站检验
#二、动态URL#
运行已经做好的博客框架,会发现一个问题,只有一个主页的空盒子,而大部分时候我们希望能够让每篇博客文章都有一个独立的页面
我第一个想到的方法是给每篇博客文章加一个view函数逻辑,然后设置一个独立的url,但是这种方法耦合性太强,而且用户不友好,缺点非常多
Django给我们提供了一个方便的解决方法,就是动态URL
现在修改my_blog/article/views.py代码
因为id是每个博文的唯一标识,所以这里使用id对数据库中的博文进行查找
在my_blog/my_blog/urls.py中修改url设置
然后在templates下建立一个用于显示单页博文的界面post.html:
可以发现只需要对home.html进行简单的修改,去掉循环就可以了
修改home.html和base.html,加入动态链接和主页,归档,专题和About Me按钮
base.html:
其中主要改动
添加了几个导航按钮,方便以后添加功能(暂时没有登录功能)
添加read more按钮
在博客文章增加一个链接,链接的href属性为{% url “detail”id=post.id %},当点击这个文章题目时,会将对应的数据库对象的id传入url中,类似url传参,这里将数据库对象唯一的id传送给url设置,url取出这个id给对应的view中的函数逻辑当做参数,这样这个id就传入对应的参数中被使用
比如:点击到的博客文章标题的对象对应的id=2,这个id被传送到name=detail的url中,‘^(P\d+)/$’正则表达式匹配后取出id,然后将id传送到article.views.detail作为函数参数,然后通过get方法获取对应的数据库对象,然后对对应的模板进行渲染,发送到浏览器中
#三、实验总结#
面对一个用户的请求(request),Django做了如下的工作
1、 Web服务器收到一个http请求
2、 Django在url.py里查找对应的Views.py函数来处理http请求
3、 Views函数调用不同的Model和Template来完成最终的展示界面
4、 Views函数返回http响应给Web服务器
在这之间,URL解析函数和Views函数之间可以使用多种方式传递参数,Views函数和Template之间也通过传递参数的方式进行合作