系統(tǒng)功能
1台囱、博客列表展示
2享幽、新增博客兜材、修改博客象踊、刪除博客琼了、搜索博客
3营曼、后臺管理
后臺管理
django自帶后臺管理系統(tǒng)Admin摔刁,被授權(quán)的用戶可以直接在后臺管理系統(tǒng)中操作數(shù)據(jù)庫吩翻。同時(shí)婴洼,我們可以按照需求對Admin進(jìn)行定制骨坑。
1、創(chuàng)建超級用戶
python manage.py createsuperuser
根據(jù)提示柬采,輸入用戶名欢唾、郵箱、密碼粉捻。
2礁遣、測試訪問
訪問地址 http://localhost:8000/admin/ ,輸入用戶名密碼肩刃,登錄后臺管理系統(tǒng)亡脸。
3、改成中文
后臺管理系統(tǒng)树酪,默認(rèn)是英文的浅碾,修改settings.py:
# LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'zh-hans'
刷新后臺管理頁面,發(fā)現(xiàn)變成了中文续语。
4垂谢、注冊model
此時(shí),我們在后臺管理中看不到article等表數(shù)據(jù)疮茄,要想顯示數(shù)據(jù)滥朱,需要在blog/admin.py中注冊model。
from django.contrib import admin
from . import models
# Register your models here.
admin.site.register(models.Article)
刷新后臺管理頁面力试,發(fā)現(xiàn)article表已經(jīng)出現(xiàn)徙邻。
5、點(diǎn)擊進(jìn)入Articles畸裳,發(fā)現(xiàn)里面有很多Article Object缰犁,因?yàn)槲覀冊赽log/models.py中添加了__str__
方法,所以顯示的名稱是文章標(biāo)題。
def __str__(self):
return self.title
頁面開發(fā)
主頁面
1帅容、在blog/urls.py中配置路由
url(r'^$', views.index, name='index'),
url(r'^index$', views.index, name='index'),
2颇象、在blog/views.py中修改index方法
def index(request):
articles = models.Article.objects.all()
return render(request, 'blog/index.html', {'articles': articles})
3、修改blog/templates/blog/index.html
<!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>博客標(biāo)題</th>
<th>發(fā)布時(shí)間</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/blog 或 http://localhost:8000/blog/index
靜態(tài)資源
blog/index.html中遣钳,沒有添加樣式。接下來麦乞,我們修改一下項(xiàng)目結(jié)構(gòu)蕴茴,把樣式表放在靜態(tài)資源目錄中。參考DJango 1.8 配置靜態(tài)資源文件可訪問 和 Django 靜態(tài)文件姐直。
1荐开、新建djsite/static/css層級目錄,在css下新建index.css简肴,內(nèi)容參見源碼分享晃听。
2、在settings.py中添加
# 設(shè)置STATIC_URL為存儲靜態(tài)文件的路徑(基于根目錄)
STATIC_URL = '/static/'
# 配置存儲靜態(tài)文件的路徑映射值砰识,這個(gè)值用于模版引用路徑的轉(zhuǎn)換
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
3能扒、修改blog/index.html為:
<!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中添加:
url(r'^(?P<article_id>[0-9]+)$', views.detail, name='detail'),
2辫狼、在blog/views.py中添加方法:
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:
<!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中添加:
url(r'^toadd$', views.toadd, name='toadd'),
2见秤、在blog/views.py添加方法:
def toadd(request):
return render(request, 'blog/add.html')
3、在blog/templates/blog中添加add.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加博客</title>
</head>
<body>
<form action="/blog/add" method="post">
<p>
<label for="title">標(biāo)題</label>
<input id="title" name="title" type="text">
</p>
<p>
<label for="content">內(nèi)容</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方法為:
@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中添加:
url(r'^toedit/(?P<article_id>[0-9]+)$', views.toedit, name='toedit'),
2突硝、在blog/views.py添加方法:
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:
<!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">標(biāo)題</label>
<input id="title" name="title" type="text" value="{{article.title}}">
</p>
<p>
<label for="content">內(nèi)容</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方法:
@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引入:
<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、創(chuàng)建static/js目錄护盈,js目錄中新建index.js:
$(function(){
$('table').on('click','.del',function(){
$that = $(this);
layer.confirm('確認(rèn)刪除挟纱?', {
btn: ['確認(rèn)','取消'] //按鈕
}, 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方法:
@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/ 紊服,點(diǎn)擊文章后面的刪除按鈕即可檀轨。
查找博客
1、在blog/urls.py中添加:
url(r'^search$', views.search, name='search')
2围苫、在blog/views.py中添加search方法:
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中添加:
<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中添加:
$('.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