一、后台管理页面构建
1、创建后台管理url
urlpatterns = [
...
# 后台管理url
re_path("cn_backend/$", views.cn_backend),
re_path("cn_backend/add_article/$", views.add_article),
...
]
2、构造视图函数
from django.contrib.auth.decorators import login_required # 装饰器:login_required()
@login_required
def cn_backend(request):
"""
后台管理页面
:param request:
:return:
"""
# 当前登录人发布过得文章列表
article_list = models.Article.objects.filter(user=request.user)
return render(request, "backend/backend.html", locals())
@login_required
def add_article(request):
"""
后台管理添加文章视图函数
:param request:
:return:
"""
if request.method == "POST":
title = request.POST.get("title")
content = request.POST.get("content")
# 生成article对象
models.Article.objects.create(title=title, content=content, user=request.user)
return redirect("/cn_backend/")
return render(request, "backend/add_article.html")
3、在templates目录下创建backend子目录,构建模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>博客后台管理 - 博客园</title>
<!-- 引入 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="/static/blog/bootstrap-3.3.7/css/bootstrap.css">
<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
<script src="/static/js/jquery-3.3.1.js"></script>
<!-- 引入 Bootstrap 核心 JavaScript 文件 -->
<script src="/static/blog/bootstrap-3.3.7/js/bootstrap.js"></script> <!--依赖jquery-->
<link rel="stylesheet" href="/static/blog/css/backend.css">
</head>
<body>
<div class="header">
<p class="title">
后台管理
<a class="info" href="/logout/">注销</a>
<span class="info"><span class="glyphicon glyphicon-user"></span> {
{ request.user.username }}</span>
</p>
</div>
<div class="container">
<div class="col-md-3">
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingOne">
<h4 class="panel-title">
<a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne"
aria-expanded="true" aria-controls="collapseOne">
操作
</a>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
<div class="panel-body">
<!--添加文章url跳转-->
<p><a href="/cn_backend/add_article/">添加文章</a