十三、Django2.1 搭建多用户的博客网站——修改和删除文章

1字数 892阅读 600

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

服务器环境搭建(选学)

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

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

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

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

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

正文:

1、删除文章

1.1 修改模板

修改 ./templates/article/column/article_list.html 中的这行代码

<td>--</td>

<td>
     <a nane="delete" href="javascript:" onclick="del_article(this, {{ article.id }})"><span class="glyphicon glyphicon-trash" style="margin-left:20px;"></span></a>
</td>

在 {% endblock %} 之前添加如下 js 代码:

<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 del_article(the, article_id){
        var article_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>是否确定删除《'+article_name+'》</p> </div>',
            btn:['确定', '取消'], yes: function(){
                $.ajax({
                    url: '{% url "article:del_article" %}',
                    type:"POST",
                    data: {"article_id":article_id},
                    success: function(e){
                        if(e=="1"){
                            parent.location.reload();
                            layer.msg("has been deleted.");
                        }else{
                            layer.msg("删除失败");
                        }
                    },
                })
            },
        });
    }

</script>

1.2 修改视图函数

在 ./article/views.py 中增加 del_article 方法

@login_required(login_url='/account/login')
@require_POST
@csrf_exempt
def del_article(request):
    article_id = request.POST['article_id']
    try:
        article = ArticlePost.objects.get(id=article_id)
        article.delete()
        return HttpResponse("1")
    except:
        return HttpResponse("2")

1.3 修改路由

在 ./article/urls.py 中增加路由

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

1.4 测试效果

运行 Django,访问 http://127.0.0.1:8000/article/article-list 点击删除图标,效果如图:

删除文章

2、修改文章

2.1 修改模板

修改 ./templates/article/column/article_list.html 中的这行代码

<td>
     <a nane="delete" href="javascript:" onclick="del_article(this, {{ article.id }})"><span class="glyphicon glyphicon-trash" style="margin-left:20px;"></span></a>
</td>

<td>
     <a name="edit" href="{% url 'article:redit_article' article.id %}"><span class="glyphicon glyphicon-pencil"></span></a>
     <a nane="delete" href="javascript:" onclick="del_article(this, {{ article.id }})"><span class="glyphicon glyphicon-trash" style="margin-left:20px;"></span></a>
</td>

创建模版 ./templates/article/column/redit_article.html

{% extends "article/base.html" %}
{% load staticfiles %}
{% block title %}article column{% endblock %}
{% block content %}
<link rel="stylesheet" href="{% static 'editor/css/style.css' %}">
<link rel="stylesheet" href="{% static 'editor/css/editormd.css' %}">
<div class="container">
    <div class="col-md-10">
        <div style="margin-left:10px">
            <form class="form-horizontal" action="." method="post">{% csrf_token %}
                <div class="row" style="margin-top: 10px;">
                    <div class="col-md-2 text-right"><span>标题:</span></div>
                    <div class="col-md-10 text-left">{{this_article_form.title}}</div>
                </div>
                <div class="row" style="margin-top: 10px;">
                    <div class="col-md-2 text-right"><span>栏目:</span></div>
                    <div class="col-md-10 text-left">
                        <select id="which_column">
                            {% for column in article_columns %}
                            {% if column == this_article_column.column %}
                            <option value="{{column.id}}" selected="selected">{{column.column}}</option>
                            {% else %}
                            <option value="{{column.id}}">{{column.column}}</option>

                            {% endif %}
                            {% endfor %}
                        </select>
                    </div>
                </div>
                <div class="row" style="margin-top: 10px;">
                    <div class="col-md-2 text-right"><span>内容:</span></div>
                    <div id="editormd" class="col-md-10 text-left">
                        <!--{{article_post_form.body}}-->
                        <textarea style="display:none;" id="id_body">
{{article.body}}
                </textarea>
                    </div>
                </div>
                <div class="row">
                    <input type="button" class="btn btn-primary btn-lg" value="发布" onclick="redit_article()">
                </div>
            </form>
        </div>
    </div>
</div>

<script type="text/javascript" src='{% static "js/jquery.js" %}'></script>
<script type="text/javascript" src='{% static "editor/editormd.min.js" %}'></script>
<script type="text/javascript" src="{% static 'js/layer.js'%}"></script>
<script type="text/javascript"> 
$(function() {
    var editor = editormd("editormd", { 
        width : "100%",
        height : 640,
        //syncScrolling : "single",
        path : "{% static 'editor/lib/' %}", 
    });
}); 

</script>

<script type="text/javascript">
function redit_article(){
    var title = $("#id_title").val();
    var column_id = $("#which_column").val(); 
    var body = $("#id_body").val();
    $.ajax({
        url: "{% url 'article:redit_article' article.id %}", 
        type: "POST",
        data: {"title":title, "body":body, "column_id":column_id}, 
        success: function(e){
            if(e=="1"){ 
                layer.msg("successful");
                location.href = "{% url 'article:article_list' %}"; 
            }else{
                layer.msg("sorry."); 
            }
        }, 
    });
}

</script>

{% endblock %}

2.2 修改视图函数

在 ./article/views.py 中增加 redit_article 方法

@login_required(login_url='/account/login')
@csrf_exempt
def redit_article(request, article_id):
    if request.method == "GET":
        article_columns = request.user.article_column.all()
        article = ArticlePost.objects.get(id=article_id)
        this_article_form = ArticlePostForm(initial={"title": article.title})
        this_article_column = article.column
        return render(request, "article/column/redit_article.html",
                      {"article": article, "article_columns": article_columns, "this_article_column": this_article_column, "this_article_form": this_article_form})
    else:
        redit_article = ArticlePost.objects.get(id=article_id)
        try:
            redit_article.column = request.user.article_column.get(id=request.POST['column_id'])
            redit_article.title = request.POST['title']
            redit_article.body = request.POST['body']
            redit_article.save()
            return HttpResponse("1")
        except:
            return HttpResponse("2")

2.3 修改路由

在 ./article/urls.py 中增加路由

path('redit-article/<int:article_id>/', views.redit_article, name="redit_article"),

2.4 测试效果

运行 Django,访问 http://127.0.0.1:8000/article/article-list 点击修改图标,效果如图:

修改文章

3、设置列表分页

3.1 修改视图函数中的 article_list 方法

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

@login_required(login_url='/account/login')
def article_list(request):
    articles_list = ArticlePost.objects.filter(author=request.user)
    paginator = Paginator(articles_list, 2)
    page = request.GET.get('page')
    try:
        current_page = paginator.page(page)
        articles = current_page.object_list
    except PageNotAnInteger:
        current_page = paginator.page(1)
        articles = current_page.object_list
    except EmptyPage:
        current_page = paginator.page(paginator.num_pages)
        articles = current_page.object_list
    return render(request, "article/column/article_list.html", {"articles": articles, "page": current_page})

3.2 创建 ./templates/paginator.html

<div class="pagination"> 
    <span class="step-links">
        {% if page.has_previous %}
        <a href="?page={{ page.previous_page_number }}">Previous</a> 
        {% endif %}
        <span class="current">
            Page {{ page.number }} of {{ page.paginator.num_pages }} 
        </span>
        {% if page.has_next %}
        <a href="?page={{ page.next_page_number }}">Next</a> {% endif %}
    </span>
</div>

3.3 引入paginator.html

在 ./templates/article/column/article_list.html 中的<table></table>之后添加这行代码

{% include "paginator.html" %}

3.4 测试效果

运行 Django,访问 http://127.0.0.1:8000/article/article-list

设置分页

推荐阅读更多精彩内容