美文网首页
六、Django文章栏目

六、Django文章栏目

作者: 途中的蜗牛 | 来源:发表于2021-01-01 11:11 被阅读0次

    1、设置栏目

    (1)创建文章管理应用

    $ python manage.py startapp article
    

    (2)将应用加入到./mysite/settings.py

    INSTALLED_APPS = [
       ...,
        'article',
    ]
    

    (3)设置栏目的数据类型
    编辑./article/models.py

    from django.db import models
    from django.contrib.auth.models import User
    
    class ArticleColumn(models.Model):
        user = models.ForeignKey(User, on_delete=models.CASCADE,related_name='article_column')
        column = models.CharField(max_length=200)
        created = models.DateField(auto_now_add=True)
    
        def __str__(self):
            return self.column
    

    进行数据迁移操作:

    $ python manage.py makemigrations
    $ python manage.py migrate
    

    (4)设置表单类
    即为上表中的colunm赋值,所以创建./article/forms.py

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

    (5)创建视图函数
    编辑./article/views.py

    from django.shortcuts import render, get_object_or_404
    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})
    

    (6)配置URL

    • 配置./mysite/urls.py
        path('article/', include('article.urls', namespace='article')),
    
    • 配置./aiticle/urls.py
    from django.urls import path
    from . import views
    
    app_name = "article"                                                                                       
    
    urlpatterns = [
        path('article-column/', views.article_column, name="article_column"),                                  
    ] 
    

    (7)前端模板
    类似于后台,其中的header.html和footer.html使用./templates下面的即可, 另外需要添加leftslider.html(左边栏)、base.html以及前端展示模板./article/column/article_column.html三个文件。

    • leftslider.html
    <div class="bg-info">
        <div class="text-center" style="margin-top: 5px;">
            <p><a href="{% url 'article:article_column'%}">栏目管理</a></p>
        </div>
    </div>
    
    • 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 '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>
    
    • 前端展示模板./article/column/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-->
            <button id= "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>
    {% endblock %}
    
    • {{ forloop.counter }} 只在循环内部使用,这里电视当前循环次数的计数器(从1开始)
    • {% empty %}如果引用的对象columns 为空,则显示,省略了if的判断。

    (8)将栏目管理放在header的user下面,即点击user可以展开看到栏目管理,修改./templates/header.html

    {% load staticfiles %}
    <div class="container">
        <nav class="navbar navbar-default" role="navigation">
            <div class="navbar-header">
            </div>
            <div>
                <ul class="nav navbar-nav" role="navigation">
                    <li><a href="{% url 'blog:blog_title' %}">BLOG</a></li>
                    <li><a href="{% url 'blog:nlp_title' %}">NLP</a></li>
                </ul>
                <ul class="nav navbar-nav navbar-right" style="margin-right:10px">
                {% if user.is_authenticated %}
                    <li>
                        <div class="dropdown" style="margin-top:8px">
                            <button class='btn btn-default dropdown-toggle' type='button' id='dropdownMenu' data-toggle='dropdown'>{{ user.username }}
                                <span class='caret'></span>
                            </button>
                            <ul class="dropdown-menu">
                                <li><a href="{% url 'article:article_column' %}">栏目管理</a></li>
                            </ul>
                        </div>
                    </li>
                    <li><a href="{% url 'account:user_logout' %}">Logout</a></li>
                {% else %}
                    <li><a href="{% url 'account:user_login' %}">LOGIN</a></li>
                {% endif %}
                </ul>
            </div>
        </nav>
    </div>
    
    <script src="{% static 'js/jquery.js' %}"></script>
    <script src="{% static 'js/bootstrap.js' %}"></script>
    

    2、增加新栏目

    (1)页面编辑
    使用layer.js,实现弹出对话框,编辑./article/column/article_column.html,将原来的button进行适当的修改

            <button id= "add_column" onclick="add_column()" class="btn btn-primary"> add column</button>
    

    当点击button按钮的时候,会出发add_column()函数,该函数代码放在文件尾部{%endblock%}之内。

    
    <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>
    

    (2)重写views.py中的article_column函数

    from django.shortcuts import render, get_object_or_404
    from django.contrib.auth.decorators import login_required
    from django.views.decorators.csrf import csrf_exempt
    from django.http import HttpResponse
    
    from .models import ArticleColumn
    from .forms import ArticleColumnForm
    
    @login_required(login_url='/account/login/')
    @csrf_exempt  # 在视图函数前面添加该装饰器,也是解决表单中CSRF问题的一种方式
    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 # 在视图函数前面添加该装饰器,也是解决表单中CSRF问题的一种方式
    • ArticleColumn.objects.filter(user_id=request.user.id,column=column_name)条件有两个:一个是当前用户,另一个是栏目名称。然后判断查询结果,如果没有改栏目名称则创建。

    3、编辑栏目

    在栏目列表中,有一列是“操作”列,可以添加“编辑”和“删除”等动作,这里主要实现“编辑”操作。
    (1)编辑页面
    修改./article/column/article_column.html,显示具体的操作。

    • 编辑操作代码
            <tr>
                <td>{{ forloop.counter }}</td>
                <td>{{ column.column }}</td>
                <td>
                    <a name="edit" href="javascript:" onclick="edit_column(this, {{ column.id }})"> 
                        <span class="glyphicon glyphicon-pencil"></span>    
                    </a>
                </td>
            </tr>
    
    • 编辑edit_column函数
        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("新的名称没有保存,修改失败。")
                            } 
                        },
                    }); 
                },
            }); 
        }
    
    

    (2)编辑视图函数./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")
    
    • @require_POST使用该装饰器的目的就是保证此视图函数只接收通过POST方式提交的数据。
    • line.save() # 实现该属性的重新赋值,要记得
      (3)配置./article/urls.py
        path('rename-column/', views.rename_article_column, name="rename_article_column"),
    

    4、删除栏目

    (1)编辑页面
    修改./article/column/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>
    
    • 编辑del_column函数
        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("删除失败");
                            }
                        },
                    })
                },
            });
        }
    

    (2)编辑视图函数./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")
    

    (3)配置./article/urls.py

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

    5、将栏目的管理权限给超级管理员

    编辑./article/admin.py

    from django.contrib import admin
    from .models import ArticleColumn
    
    class ArticleColumnAdmin(admin.ModelAdmin): 
        list_display = ('column', 'created', 'user') 
        list_filter = ("column",)
        
    admin.site.register(ArticleColumn, ArticleColumnAdmin)
    

    参考:
    1、跟老齐学python Django实战

    相关文章

      网友评论

          本文标题:六、Django文章栏目

          本文链接:https://www.haomeiwen.com/subject/jsoloktx.html