十、Django2.1 搭建多用户的博客网站——文章栏目

96
麦典威
0.7 2019.01.29 10:08* 字数 1116

目录:Django 2.1 从零开始搭建博客网站系列

服务器环境搭建(选学)

小试牛刀——简单的博客网站

庖丁解牛——多用户的博客网站之用户模块

庖丁解牛——多用户的博客网站之文章模块

华丽转身——多用户的博客网站之扩展功能

项目源码下载:https://github.com/jt1024/lehehe

正文:

按照内容产生的方式来分类,可以分为两类:UGC(用户生成内容)和 PGC(专业生产内容)。我们要搭建的网站是UGC类型,这种网站分为前后两部分,“前面”是让访客浏览网站上的文档,“后面”是用户管理自己的文章。

1、创建应用article

python manage.py startapp article

在 ./lehehe/settings.py 中 修改 INSTALLED_APPS

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
    'account',
    'article',  # 新增
]

创建 ./article/urls.py

from django.urls import path

app_name = 'article'  # 一定要写这一行,否则html中会报错 'article' is not a registered namespace

urlpatterns = [

]

2、设置文章栏目

2.1 栏目的数据模型

编辑 ./article/models.py

from django.db import models
from django.contrib.auth.models import User


class ArticleColumn(models.Model):
    user = models.ForeignKey(User, related_name='article_column', on_delete=models.CASCADE)
    column = models.CharField(max_length=200)
    created = models.DateField(auto_now_add=True)

    def __str__(self):
        return self.column

执行以下命令迁移数据

python manage.py make migrations
python manage.py migrate

此时生成的数据表如图:


article_articlecolumn.png

创建 ./article/forms.py

from django import forms
from .models import ArticleColumn


class ArticleColumnForm(forms.ModelForm):
    class Meta:
        model = ArticleColumn
        fields = ("column",)

2.2 栏目的视图函数

编辑 ./article/views.py

from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from .models import ArticleColumn


@login_required(login_url='/account/login/')
def article_column(request):
    columns = ArticleColumn.objects.filter(user=request.user)
    return render(request, "article/column/article_column.html", {"columns": columns})

编辑 ./article/urls.py

from django.urls import path
from . import views

app_name = 'article'  # 一定要写这一行,否则html中会报错 'article' is not a registered namespace

urlpatterns = [
    path('article-column/', views.article_column, name="article_column"),
]

2.3 栏目的模板

文章管理的后台的header应与前台的header不同,footer可以不用变。
创建 ./templates/article/header.html

{% load staticfiles %}
<div class="container">
    <nav class="navbar navbar-default" role="navigation">
        <div class="navbar-header">
            <a class="navbar-brand" href="http://www.taoge100.com"><img src="{% static '/images/logo.png' %}" width="100px"></a>
        </div>
        <div>
            <ul class="nav navbar-nav" role="tablist">
                <li><a href="{% url 'article:article_column' %}">文章管理</a></li>
            </ul>
            <ul class="nav navbar-nav navbar-right" style="margin-right:10px">
                <li><a href="{% url 'blog:blog_list' %}">网站首页</a></li>
                <li><a href="#" style="text-color:red">{{ user.username }}</a></li>
                <li><a href="{% url 'account:user_logout' %}">Logout</a></li>
            </ul>
        </div>
    </nav>
</div>

创建 ./templates/article/leftslide.html

<div class="bg-info">
    <div class="text-center" style="margin-top: 5px;">
        <p><a href="{% url 'article:article_column'%}">栏目管理</a></p>
    </div>
</div>

创建 ./templates/article/base.html

{% load staticfiles %}
<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{% block title %}{% endblock %}</title>
    <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}">
</head>
<body>
<div class="container">
    {% include 'article/header.html' %}
    <div class="col-md-2">
        {% include 'article/leftslider.html' %}
    </div>
    <div class="col-md-10">
        {% block content %}
        {% endblock %}
    </div>
    {% include 'footer.html' %}
</div>
</body>
</html>

创建 ./templates/article/article_column.html

{% extends "article/base.html" %}
{% load staticfiles %}
{% block title %}article column{% endblock %}
{% block content %}
<div>
    <p class="text-right">
        <button class="btn btn-primary">add column</button>
    </p>
    <table class="table table-hover">
        <tr>
            <td>序号</td>
            <td>栏目名称</td>
            <td>操作</td>
        </tr>
        {% for column in columns %}
        <tr>
            <td>{{ forloop.counter }}</td>
            <td>{{ column.column }}</td>
            <td>--</td>
        </tr>
        {% empty %}
        <p>还没有设置栏目,太懒了。</p>
        {% endfor %}
    </table>
</div>

{% endblock %}

修改 ./templates/header.html 中的下拉框

<ul class="dropdown-menu">
                            <li><a href="{% url 'account:my_information' %}">个人信息</a></li>
                            <li><a href="{% url 'account:edit_my_information' %}">完善信息</a></li>
                            <li><a href="{% url 'account:password_change' %}">修改密码</a></li>
                            <li><a href="{% url 'account:password_reset' %}">密码重置</a></li>
                            <li><a href="{% url 'article:article_column' %}">后台管理</a></li><!--新增-->
                        </ul>

登录后,访问 http://127.0.0.1:8000/article/article-column/ 页面如图

文章管理后台

2.4 增加新栏目

修改 ./templates/article/article_column.html 使点击 "add column" 按钮有效

{% extends "article/base.html" %}
{% load staticfiles %}
{% block title %}article column{% endblock %}
{% block content %}
<div>
    <p class="text-right">
        <!--<button class="btn btn-primary">add column</button>-->
        <button id="add_column" onclick="add_column()" class="btn btn-primary"> add column</button>
    </p>
    <table class="table table-hover">
        <tr>
            <td>序号</td>
            <td>栏目名称</td>
            <td>操作</td>
        </tr>
        {% for column in columns %}
        <tr>
            <td>{{ forloop.counter }}</td>
            <td>{{ column.column }}</td>
            <td>--</td>
        </tr>
        {% empty %}
        <p>还没有设置栏目,太懒了。</p>
        {% endfor %}
    </table>
</div>

<script type="text/javascript" src='{% static "js/jquery.js" %}'></script>
<script type="text/javascript" src="{% static 'js/layer.js'%}"></script>
<script type="text/javascript">
    function add_column() {
        var index = layer.open({
            type: 1,
            skin: "layui-layer-rim",
            area: ["400px", "200px"],
            title: "新增栏目",
            content: '<div class="text-center" style="margin-top:20px"><p> 请输入新的栏目名称</p><p>{{ column_form.column }}</p></div>',
            btn: ['确定', '取消'],
            yes: function (index, layero) {
                column_name = $('#id_column').val();
                $.ajax({
                    url: '{% url "article:article_column" %}',
                    type: 'POST',
                    data: { "column": column_name },
                    success: function (e) {
                        if (e == "1") {
                            parent.location.reload();
                            layer.msg("good");
                        } else {
                            layer.msg("此栏目已有,请更换名称")
                        }
                    },
                });
            },
            btn2: function (index, layero) {
                layer.close(index);
            }
        });
    }
</script>
{% endblock %}

修改 ./article/views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from .models import ArticleColumn
from .forms import ArticleColumnForm


@login_required(login_url='/account/login/')
@csrf_exempt
def article_column(request):
    if request.method == "GET":
        columns = ArticleColumn.objects.filter(user=request.user)
        column_form = ArticleColumnForm()
        return render(request, "article/column/article_column.html", {"columns": columns, 'column_form': column_form})

    if request.method == "POST":
        column_name = request.POST['column']
        columns = ArticleColumn.objects.filter(user_id=request.user.id, column=column_name)
        if columns:
            return HttpResponse('2')
        else:
            ArticleColumn.objects.create(user=request.user, column=column_name)
            return HttpResponse("1")

@csrf_exempt 在视图函数中使用这个装饰器,是另一种操作POST时的加密机制,之前我们使用过 csrf.js 文件,表单中还使用过 {% csrf_token %}

点击“add column” 按钮,弹出下图的弹窗,填写栏目名称即可增加新栏目


增加新栏目
栏目列表

2、编辑文章栏目

修改 ./templates/article/article_column.html 中的 <td>--</td>

<td>
      <a name="edit" href="javascript:" onclick="edit_column(this, {{ column.id }})"> <span class="glyphicon glyphicon-pencil"></span></a>
</td>

继续修改 ./templates/article/article_column.html 在后面添加 javascript 代码

function edit_column(the, column_id){
        var name = $(the).parents("tr").children("td").eq(1).text();
        var index = layer.open({
            type: 1,
            skin: "layui-layer-rim",
            area: ["400px", "200px"],
            title: "编辑栏目",
            content: '<div class="text-center" style="margin-top:20px"> <p>请编辑的栏目名称</p><p><input type="text" id="new_name" value="'+name+'"></p> </div>',
            btn:['确定', '取消'],
            yes: function(index, layero){
                new_name = $("#new_name").val();
                $.ajax({
                    url: "{% url 'article:rename_article_column' %}",
                    type: "POST",
                    data: {"column_id": column_id, "column_name": new_name},
                    success: function(e){
                        if(e=="1"){
                            parent.location.reload();
                            layer.msg("good");
                        }else{
                            layer.msg("新的名称没有保存,修改失败。")
                        }
                    },
                });
            },
        });
    }

修改 ./article/views.py

from django.views.decorators.http import require_POST

@login_required(login_url='/account/login')
@require_POST
@csrf_exempt
def rename_article_column(request):
    column_name = request.POST["column_name"]
    column_id = request.POST['column_id']
    try:
        line = ArticleColumn.objects.get(id=column_id)
        line.column = column_name
        line.save()
        return HttpResponse("1")
    except:
        return HttpResponse("0")

修改 ./article/urls.py 添加新的路由

path('rename-article-column/', views.rename_article_column, name="rename_article_column"),

点击编辑图标,页面如图:


编辑栏目

3、删除文章栏目

修改 ./templates/article/article_column.html 在“编辑”图标后,增加“删除”

<td>
     <a name="edit" href="javascript:" onclick="edit_column(this, {{ column.id }})"> <span class="glyphicon glyphicon-pencil"></span></a>
     <a name="delete" href="javascript:" onclick="del_column(this, {{ column.id }})"><span class="glyphicon glyphicon-trash" style="margin-left:20px;"></span></a>
</td>

继续修改 ./templates/article/article_column.html 在后面添加 javascript 代码

function del_column(the, column_id){
        var name = $(the).parents("tr").children("td").eq(1).text();
        layer.open({
            type: 1,
            skin: "layui-layer-rim",
            area: ["400px", "200px"],
            title: "删除栏目",
            content: '<div class="text-center" style="margin-top:20px"><p>是否确定删除{'+name+'}栏目</p> </div>',
            btn:['确定', '取消'], yes: function(){
                $.ajax({
                    url: '{% url "article:del_article_column" %}',
                    type:"POST",
                    data: {"column_id":column_id},
                    success: function(e){
                        if(e=="1"){
                            parent.location.reload();
                            layer.msg("has been deleted.");
                        }else{
                            layer.msg("删除失败");
                        }
                    },
                })
            },
        });
    }

修改 ./article/views.py

@login_required(login_url='/account/login')
@require_POST
@csrf_exempt
def del_article_column(request):
    column_id = request.POST["column_id"]
    try:
        line = ArticleColumn.objects.get(id=column_id)
        line.delete()
        return HttpResponse("1")
    except:
        return HttpResponse("2")

修改 ./article/urls.py 添加新的路由

path('del-article-column/', views.del_article_column, name="del_article_column"),

点击删除图标,页面如图:


删除栏目