Django开发简单Blog系统——中

系统功能

1、博客列表展示
2、新增博客、修改博客、删除博客、搜索博客
3、后台管理

后台管理

django自带后台管理系统Admin,被授权的用户可以直接在后台管理系统中操作数据库。同时,我们可以按照需求对Admin进行定制。

1、创建超级用户
python manage.py createsuperuser
根据提示,输入用户名、邮箱、密码。

2、测试访问
访问地址 http://localhost:8000/admin/ ,输入用户名密码,登录后台管理系统。

3、改成中文
后台管理系统,默认是英文的,修改settings.py:

1
2
# LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'zh-hans'

刷新后台管理页面,发现变成了中文。

4、注册model
此时,我们在后台管理中看不到article等表数据,要想显示数据,需要在blog/admin.py中注册model。

1
2
3
4
5
6
7
from django.contrib import admin
from . import models

# Register your models here.


admin.site.register(models.Article)

刷新后台管理页面,发现article表已经出现。

5、点击进入Articles,发现里面有很多Article Object,因为我们在blog/models.py中添加了__str__方法,所以显示的名称是文章标题。

1
2
def __str__(self):
return self.title

页面开发

主页面

1、在blog/urls.py中配置路由

1
2
url(r'^$', views.index, name='index'),
url(r'^index$', views.index, name='index'),

2、在blog/views.py中修改index方法

1
2
3
def index(request):
articles = models.Article.objects.all()
return render(request, 'blog/index.html', {'articles': articles})

3、修改blog/templates/blog/index.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h2>博客列表</h2>
<div class="menu">
<input class="search-input" type="text">
<span class="search">搜索</span>
<a class="add" href="/blog/toadd">添加</a>
</div>
<table>
<thead>
<th>博客标题</th>
<th>发布时间</th>
<th>操作</th>
</thead>
<tbody>
{% for article in articles %}
<tr data-id="{{article.id}}">
<td><a href="/blog/{{article.id}}">{{article.title}}</a></td>
<td>{{article.pub_time}}</td>
<td>
<span class="del">删除</span>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>

4、测试访问
访问地址 http://localhost:8000/bloghttp://localhost:8000/blog/index

静态资源

blog/index.html中,没有添加样式。接下来,我们修改一下项目结构,把样式表放在静态资源目录中。参考DJango 1.8 配置静态资源文件可访问Django 静态文件

1、新建djsite/static/css层级目录,在css下新建index.css,内容参见源码分享。

2、在settings.py中添加

1
2
3
4
5
6
# 设置STATIC_URL为存储静态文件的路径(基于根目录)
STATIC_URL = '/static/'
# 配置存储静态文件的路径映射值,这个值用于模版引用路径的转换
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)

3、修改blog/index.html为:

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
{% load staticfiles %}
<link rel="stylesheet" href="{%static 'css/index.css'%}">
<title>首页</title>
</head>
<body>
<!--不变-->
</body>
</html>

查看博客页面

1、在blog/urls.py中添加:

1
url(r'^(?P<article_id>[0-9]+)$', views.detail, name='detail'),

2、在blog/views.py中添加方法:

1
2
3
4
def detail(request,article_id):
article = models.Article.objects.get(pk=article_id)
return render(request, 'blog/article.html',
{'article': article})

3、在blog/templates/blog中添加article.html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
{% load staticfiles %}
<link rel="stylesheet" href="{%static 'css/article.css'%}">
<title>{{article.title}}</title>
</head>
<body>
<h2>{{article.title}}</h2>
<div>
<p>{{article.content}}</p>
</div>
<div>
<a class="edit" href="/blog/toedit/{{article.id}}">编辑</a>
</div>

</body>
</html>

4、测试访问
访问地址 http://localhost:8000/blog/1

添加博客页面

1、在blog/urls.py中添加:

1
url(r'^toadd$', views.toadd, name='toadd'),

2、在blog/views.py添加方法:

1
2
def toadd(request):
return render(request, 'blog/add.html')

3、在blog/templates/blog中添加add.html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加博客</title>
</head>
<body>
<form action="/blog/add" method="post">
<p>
<label for="title">标题</label>
<input id="title" name="title" type="text">
</p>

<p>
<label for="content">内容</label>
<textarea id="content" name="content" id="" cols="30" rows="10"></textarea>
</p>
<p>
<input type="submit" value="确定">
</p>
</form>
</body>
</html>

4、修改blog/views.py中的add方法为:

1
2
3
4
5
6
7
8
9
10
11
12
@csrf_exempt
def add(request):
title = request.POST.get('title', 'defaultTitle')
content = request.POST.get('content', 'defaultContent')

pub_time = utc2local(timezone.now())
LOCAL_FORMAT = "%Y-%m-%d %H:%M:%S"
pub_time = pub_time.strftime(LOCAL_FORMAT)

models.Article.objects.create(title=title, content=content, pub_time=pub_time)
articles = models.Article.objects.all()
return render(request, 'blog/index.html',{'articles': articles})

5、测试访问
访问地址 http://localhost:8000/blog/toadd

修改博客页面

1、在blog/urls.py中添加:

1
url(r'^toedit/(?P<article_id>[0-9]+)$', views.toedit, name='toedit'),

2、在blog/views.py添加方法:

1
2
3
def toedit(request, article_id):
article = models.Article.objects.get(pk=article_id)
return render(request, 'blog/edit.html', {'article': article})

3、在blog/templates/blog中添加edit.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>修改博客</title>
</head>
<body>
<form action="/blog/edit" method="post">
<p style="display: none;">
<input name="id" type="text" value="{{article.id}}">
</p>
<p>
<label for="title">标题</label>
<input id="title" name="title" type="text" value="{{article.title}}">
</p>

<p>
<label for="content">内容</label>
<textarea id="content" name="content" id="" cols="30" rows="10">{{article.content}}</textarea>
</p>
<p>
<input type="submit" value="确定">
</p>
</form>
</body>
</html>

4、修改blog/views.py中的edit方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@csrf_exempt
def edit(request):
article_id = request.POST.get('id', 0)
title = request.POST.get('title', 'defaultTitle')
content = request.POST.get('content', 'defaultContent')
pub_time = utc2local(timezone.now())
LOCAL_FORMAT = "%Y-%m-%d %H:%M:%S"
pub_time = pub_time.strftime(LOCAL_FORMAT)

article = models.Article.objects.get(pk=article_id)
article.title = title
article.content = content
article.pub_time = pub_time
article.save()

articles = models.Article.objects.all()
return render(request, 'blog/index.html', {'articles': articles})

删除博客

1、修改blog/templates/blog/index.html,添加js引入:

1
2
3
4
<script src="{% static 'lib/jquery/jquery.min.js'%}"></script>
<script src="{% static 'lib/layer/layer.js'%}"></script>
<script src="{% static 'lib/art-template/dist/template-native.js'%}"></script>
<script src="{% static 'js/index.js'%}"></script>

2、创建static/js目录,js目录中新建index.js:

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
$(function(){
$('table').on('click','.del',function(){
$that = $(this);
layer.confirm('确认删除?', {
btn: ['确认','取消'] //按钮
}, function(){
var $tr = $that.parents('tr');
var id = $tr.attr('data-id');
$.ajax({
url: '/blog/delete',
type: 'POST',
dataType: 'json',
data: {id: id},
success: function(data){
console.log(data);
if(data.code == '0'){
$tr.remove();
layer.msg('删除成功');
}
},
error: function(xhr){
console.log(xhr);
}
});
}, function(){
// nothing
});

});
});

3、修改blog/views.py中的delete方法:

1
2
3
4
5
6
@csrf_exempt
def delete(request):
article_id = request.POST.get('id', 0)
models.Article.objects.get(pk=article_id).delete()
result = {'code': 0, 'ext': 'success'}
return HttpResponse(json.dumps(result, ensure_ascii=False))

4、测试访问
访问地址 http://localhost:8000/blog/ ,点击文章后面的删除按钮即可。

查找博客

1、在blog/urls.py中添加:

1
url(r'^search$', views.search, name='search')

2、在blog/views.py中添加search方法:

1
2
3
4
5
6
7
8
9
10
11
12
from django.db.models import Q
@csrf_exempt
def search(request):
key = request.POST.get('key')
articles = models.Article.objects.filter(Q(title__contains=key) | Q(content__contains=key))
json_data = serializers.serialize("json", articles)
dict_data = json.loads(json_data)
result = {
'code': 0,
'ext': 'success',
'articles': dict_data}
return HttpResponse(json.dumps(result, ensure_ascii=False))

3、在blog/templates/blog/index.html中添加:

1
2
3
4
5
6
7
8
9
10
11
12
<script type="text/template" id="tr_template">
<% for(var i = 0 ; i < articles.length ; i ++){ %>
<% var article = articles[i]; %>
<tr data-id="<%=article.pk%>">
<td><a href="/blog/<%=article.pk%>"><%=article.fields.title%></a></td>
<td><%=article.fields.pub_time%></td>
<td>
<span class="del">删除</span>
</td>
</tr>
<% } %>
</script>

4、在index.js中添加:

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
$('.search').on('click',function(){
var key = $('.search-input').val();
$.ajax({
url: '/blog/search',
type: 'POST',
dataType: 'json',
data: {key: key},
success: function(data){
console.log(data);
if(data.code == '0'){
var html = template('tr_template',{articles: data.articles});
$('tbody').html(html);
}
},
error: function(xhr){
console.log(xhr);
}
});
});

$('.search-input').keypress(function(event) {
var key = event.which;
// console.log(key);
if(key == 13){
//do something
$('.search').trigger('click');
}
});

效果演示

源码分享

https://github.com/voidking/djsite/releases/tag/v0.2.0

书签

django入门与实践

0%