Django Template和动态URL

Template

Template初探

到目前为止我们只是简单的将后端数据显示到页面上, 没有涉及到HTML代码, 而优雅的网站总算通过CSS+HTML, 甚至还有强大的JS的支持.

在这个教程中要打造一个Blog, 所以我们设置一个Blog界面, 原本打算使用Bootstrap作为前段的工具, 不过经过@游逸的建议, 使用了更加轻量级的Pure, 同样是响应式页面设置, 这也将是未来的主流吧..

在my_blog下添加文件名, 文件夹名为templates

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
$ mkdir templates

#看到当前文件构成
my_blog
├── article
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-34.pyc
│ │ ├── admin.cpython-34.pyc
│ │ ├── models.cpython-34.pyc
│ │ └── views.cpython-34.pyc
│ ├── admin.py
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ ├── __init__.py
│ │ └── __pycache__
│ │ ├── 0001_initial.cpython-34.pyc
│ │ └── __init__.cpython-34.pyc
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── db.sqlite3
├── manage.py
├── my_blog
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-34.pyc
│ │ ├── settings.cpython-34.pyc
│ │ ├── urls.cpython-34.pyc
│ │ └── wsgi.cpython-34.pyc
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── templates

1.7/1.8版本Django已经修改的template添加形式

my_blog/my_blog/settings.py下设置templates的位置

1
2
3
4
5
6
#尝试这种写法
TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates')
TEMPLATES = (
...
DIRS: [TEMPLATE_PATH],
)

意思是告知项目templates文件夹在项目根目录下

第一个template

templates/test.html 简单第一个 template html文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!--在test.html文件下添加-->
<!DOCTYPE html>
<html>
<head>
<title>Just test template</title>
<style>
body {
background-color: red;
}
em {
color: LightSeaGreen;
}
</style>
</head>
<body>
<h1>Hello World!</h1>
<strong>{{ current_time }}</strong>
</body>
</html>

其中

1
{{ current_time }}

是Django Template中变量的表示方式

在article/views.py中添加一个函数逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from django.shortcuts import render
from django.http import HttpResponse
from article.models import Article
from datetime import datetime

# Create your views here.
def home(request):
return HttpResponse("Hello World, Django")

def detail(request, my_args):
post = Article.objects.all()[int(my_args)]
str = ("title = %s, category = %s, date_time = %s, content = %s"
% (post.title, post.category, post.date_time, post.content))
return HttpResponse(str)

def test(request) :
return render(request, 'test.html', {'current_time': datetime.now()})

render()函数中第一个参数是request 对象, 第二个参数是一个模板名称,第三个是一个字典类型的可选参数. 它将返回一个包含有给定模板根据给定的上下文渲染结果的 HttpResponse对象。

然后设置对应的url在my_blog/my_blog/urls.py下

1
url(r'^test/$', views.test),

重新启动服务器python manage.py runserver localhost:9000, 然后在浏览器中输入http://localhost:9000/test/, 可以看到

正式编写template

在template文件夹下增加base.html, 并在其中增加如下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="A layout example that shows off a blog page with a list of posts.">

<title>Andrew Liu Blog</title>
<link rel="stylesheet" href="http://labfile.oss.aliyuncs.com/courses/487/pure-min.css">
<link rel="stylesheet" href="http://labfile.oss.aliyuncs.com/courses/487/grids-responsive-min.css">
<link rel="stylesheet" href="http://labfile.oss.aliyuncs.com/courses/487/blog.css">
</head>
<body>
<div id="layout" class="pure-g">
<div class="sidebar pure-u-1 pure-u-md-1-4">
<div class="header">
<h1 class="brand-title">Andrew Liu Blog</h1>
<h2 class="brand-tagline">Snow Memory</h2>
<nav class="nav">
<ul class="nav-list">
<li class="nav-item">
<a class="pure-button" href="https://github.com/Andrew-liu">Github</a>
</li>
<li class="nav-item">
<a class="pure-button" href="http://weibo.com/dinosaurliu">Weibo</a>
</li>
</ul>
</nav>
</div>
</div>

<div class="content pure-u-1 pure-u-md-3-4">
<div>
{% block content %}
{% endblock %}
<div class="footer">
<div class="pure-menu pure-menu-horizontal pure-menu-open">
<ul>
<li><a href="http://andrewliu.tk/about/">About Me</a></li>
<li><a href="http://twitter.com/yuilibrary/">Twitter</a></li>
<li><a href="http://github.com/yahoo/pure/">GitHub</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>

</body>
</html>

上面这段html编写的页面是一个模板, 其中]

1
{% block content %} {% endblock %}

字段用来被其他继承这个基类模板进行重写

我们继续在templates文件夹下添加home.html文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{% extends "base.html" %}

{% block content %}
<div class="posts">
{% for post in post_list %}
<section class="post">
<header class="post-header">
<h2 class="post-title">{{ post.title }}</h2>

<p class="post-meta">
Time: <a class="post-author" href="#">{{ post.date_time }}</a> <a class="post-category post-category-js" href="#">{{ post.category }}</a>
</p>
</header>

<div class="post-description">
<p>
{{ post.content }}
</p>
</div>
</section>
{% endfor %}
</div><!-- /.blog-post -->
{% endblock %}

其中

1
2
3
- {% for <element> in <list> %}与{% endfor %}成对存在, 这是template中提供的for循环tag
- {% if <elemtnt> %} {% else %} {% endif %}是template中提供的if语句tag
- template中还提供了一些过滤器

然后修改my_blog/article/views.py, 并删除test.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse
from article.models import Article
from datetime import datetime

# Create your views here.
def home(request):
post_list = Article.objects.all() #获取全部的Article对象
return render(request, 'home.html', {'post_list' : post_list})
修改my_blog/my_blog/urls.py:

from django.conf.urls import url
from django.contrib import admin
from article import views
urlpatterns = [

url(r'^admin/', admin.site.urls),
url(r'^$', views.home),
]

现在重新打开http://localhost:9000/, 发现Blog的整理框架已经基本完成, 到现在我们已经了解了一些Django的基本知识, 搭建了简单地Blog框架, 剩下的就是给Blog添加功能

查看当前整个程序的目录结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
my_blog
├── article
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-34.pyc
│ │ ├── admin.cpython-34.pyc
│ │ ├── models.cpython-34.pyc
│ │ └── views.cpython-34.pyc
│ ├── admin.py
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ ├── __init__.py
│ │ └── __pycache__
│ │ ├── 0001_initial.cpython-34.pyc
│ │ └── __init__.cpython-34.pyc
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── db.sqlite3
├── manage.py
├── my_blog
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-34.pyc
│ │ ├── settings.cpython-34.pyc
│ │ ├── urls.cpython-34.pyc
│ │ └── wsgi.cpython-34.pyc
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── templates
├── base.html
└── home.html

将代码上传到Github

也可以选择保存代码到实验楼的内置代码库。

在github中新建仓库my_blog_tutorial, 填写简单的描述

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#查看当前目录位置
$ pwd
/Users/andrew_liu/Python/Django/my_blog

#在项目的根目录下初始化git
git init
Initialized empty Git repository in/Users/andrew_liu/Python/Django/my_blog/.git/

#添加远程github
$ git remote add blog git@github.com:Andrew-liu/my_blog_tutorial.git
在根目录下增加`.gitignore'和'LICENSE'和'README.md'文件

#添加所有文件
$ git add .

#查看当前状态
$ git status

#commit操作
$ git commit -m "django tutorial init"

#上传github
$ git push -u blog master
Counting objects: 23, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (22/22), done.
Writing objects: 100% (23/23), 19.56 KiB | 0 bytes/s, done.
Total 23 (delta 1), reused 0 (delta 0)
To git@github.com:Andrew-liu/my_blog_tutorial.git
* [new branch] master -> master
Branch master set up to track remote branch master from blog

动态URL

动态URL

运行已经做好的博客框架, 会发现一个问题, 只有一个主页的空盒子, 而大部分时候我们希望能够让每篇博客文章都有一个独立的页面.

我第一个想到的方法是给每篇博客文章加一个view函数逻辑, 然后设置一个独立的url(我不知道语言比如PHP, 或者web框架rail等是如果解决的, 我是第一次仔细的学习web框架, 也没有前端开发经验), 但是这种方法耦合性太强, 而且用户不友好, 缺点非常多

Django给我们提供了一个方便的解决方法, 就是动态URL
现在修改my_blog/article/views.py代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse
from article.models import Article
from datetime import datetime
from django.http import Http404

# Create your views here.
def home(request):
post_list = Article.objects.all() #获取全部的Article对象
return render(request, 'home.html', {'post_list' : post_list})

def detail(request, id):
try:
post = Article.objects.get(id=str(id))
except Article.DoesNotExist:
raise Http404
return render(request, 'post.html', {'post' : post})

因为id是每个博文的唯一标识, 所以这里使用id对数据库中的博文进行查找

在my_blog/my_blog/urls.py中修改url设置:

1
2
3
4
5
6
7
8
9
10
11
12
13
from django.conf.urls import url
from django.contrib import admin
from article import views

urlpatterns = [
# Examples:
# url(r'^$', 'my_blog.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),

url(r'^admin/', include(admin.site.urls)),
url(r'^$', views.home, name = 'home'),
url(r'^(?P<id>\d+)/$', views.detail, name='detail'),
]

然后在templates下建立一个用于显示单页博文的界面 post.html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#post.html
{% extends "base.html" %}

{% block content %}
<div class="posts">
<section class="post">
<header class="post-header">
<h2 class="post-title">{{ post.title }}</h2>

<p class="post-meta">
Time: <a class="post-author" href="#">{{ post.date_time|date:"Y /m /d"}}</a> <a class="post-category post-category-js" href="#">{{ post.category }}</a>
</p>
</header>

<div class="post-description">
<p>
{{ post.content }}
</p>
</div>
</section>
</div><!-- /.blog-post -->
{% endblock %}

可以发现只需要对home.html进行简单的修改, 去掉循环就可以了.

修改home.html和base.html, 加入动态链接和主页, 归档, 专题和About Me按钮

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!--home.html-->
{% extends "base.html" %}

{% block content %}
<div class="posts">
{% for post in post_list %}
<section class="post">
<header class="post-header">
<h2 class="post-title"><a href="{% url "detail" id=post.id %}">{{ post.title }}</a></h2>

<p class="post-meta">
Time: <a class="post-author" href="#">{{ post.date_time |date:"Y /m /d"}}</a> <a class="post-category post-category-js" href="#">{{ post.category }}</a>
</p>
</header>

<div class="post-description">
<p>
{{ post.content }}
</p>
</div>
<a class="pure-button" href="{% url "detail" id=post.id %}">Read More >>> </a>
</section>
{% endfor %}
</div><!-- /.blog-post -->
{% endblock %}

base.html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<!--base.html-->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="A layout example that shows off a blog page with a list of posts.">

<title>Andrew Liu Blog</title>
<link rel="stylesheet" href="http://labfile.oss.aliyuncs.com/courses/487/pure-min.css">
<link rel="stylesheet" href="http://labfile.oss.aliyuncs.com/courses/487/grids-responsive-min.css">
<link rel="stylesheet" href="http://labfile.oss.aliyuncs.com/courses/487/blog.css">

</head>
<body>
<div id="layout" class="pure-g">
<div class="sidebar pure-u-1 pure-u-md-1-4">
<div class="header">
<h1 class="brand-title"><a href="{% url "home" %}">Andrew Liu Blog</a></h1>
<h2 class="brand-tagline">Snow Memory</h2>
<nav class="nav">
<ul class="nav-list">
<li class="nav-item">
<a class="button-success pure-button" href="/">Home</a>
</li>
<li class="nav-item">
<a class="button-success pure-button" href="/">Archive</a>
</li>
<li class="nav-item">
<a class="pure-button" href="https://github.com/Andrew-liu/my_blog_tutorial">Github</a>
</li>
<li class="nav-item">
<a class="button-error pure-button" href="http://weibo.com/dinosaurliu">Weibo</a>
</li>
<li class="nav-item">
<a class="button-success pure-button" href="/">Pages</a>
</li>
<li class="nav-item">
<a class="button-success pure-button" href="/">About Me</a>
</li>
</ul>
</nav>
</div>
</div>


<div class="content pure-u-1 pure-u-md-3-4">
<div>
{% block content %}
{% endblock %}
<div class="footer">
<div class="pure-menu pure-menu-horizontal pure-menu-open">
<ul>
<li><a href="http://andrewliu.tk/about/">About Me</a></li>
<li><a href="http://twitter.com/yuilibrary/">Twitter</a></li>
<li><a href="http://github.com/yahoo/pure/">GitHub</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>

</body>
</html>

其中主要改动

1
2
3
4
5
6
7
 - 添加了几个导航按钮, 方便以后添加功能(暂时不添加登陆功能)
- 添加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方法获取对应的数据库对象, 然后对对应的模板进行渲染, 发送到浏览器中..

此时重新运行服务器, 然后在浏览器中输入http://localhost:9000/点击对应的博客文章题目, 可以成功的跳转到一个独立的页面中