您现在的位置是:网站首页>>编程开发编程开发

Django个人博客开发(六)admin 管理后台

发布时间:2018-04-14 10:04:54分类:编程开发阅读:1223

    概述

    Django自带的后台管理可以快速便捷管理数据。后台管理可以在各个appadmin.py文件中进行控制。通过manage.py命令行创建超级用户及密码,然后登录后台进行管理操作。自带的默认后台简略,因此需要在blog/admin.py文件中进行相应的自定义。通过添加富文本编辑器,对文章内容部分进行可视化的富文本编辑操作。

    1、添加超级用户

    (VENV_PY35) E:\Program_Code\PyProject\xdsite>python manage.py createsuperuser

    2、登录体验管理后台

    默认管理后台只有用户及组管理模块,要显示其它的管理模块,需要在相应appadmin.py文件中进行注册。


    3、通过blog/admin.py文件,自定义管理后台

    from django.contrib import admin
    from .models import Category, Tag, Article, Comment, Links
    
    # Register your models here.
    
    # 使用装饰器注册模型
    # Category模型管理器
    @admin.register(Category)
    class CategoryAdmin(admin.ModelAdmin):
        list_display = ('name', 'index')
        search_fields = ('name',)
        list_editable = ('index',)
    
    # Tag模型管理器
    @admin.register(Tag)
    class TagAdmin(admin.ModelAdmin):
        list_display = ('name', 'is_display')
        list_filter = ('is_display',)
        list_editable = ('is_display',)
    
    # Article模型管理器
    @admin.register(Article)
    class ArticleAdmin(admin.ModelAdmin):
        exclude = ('id', 'slug', 'publish')
        list_display = ('title', 'slug', 'hits', 'is_recommend', 'publish', 'category')
        filter_horizontal = ('tag',)
        list_editable = ('hits', 'is_recommend',)
        list_filter = ('category',)
        date_hierarchy = 'publish'
    
    # Comment模型管理器
    @admin.register(Comment)
    class CommentAdmin(admin.ModelAdmin):
        list_display = ('username', 'email', 'article', 'pid', 'publish')
    
    # Links模型管理器
    @admin.register(Links)
    class LinksAdmin(admin.ModelAdmin):
        list_display = ('title', 'url', 'publish', 'index')
        list_editable = ('url', 'index')
    

    4、添加富文本编辑器Kindeditor

    4.1kindeditor富文本编辑器获取

    管网:http://kindeditor.net

    4.2kindeditor-4.1.11-zh-CN.zip解包删除其它编程语言环境下才需要使用的目录(红色框内删除)


    4.3在项目根目录下创建文件上传目录uploads,然后将kindeditor富文本编辑器源文件放置到项目静态文件目录中,并在源文件目录下添加配置文件config.js,便于后续引用


    其中,编辑器配置文件config.js内容为:

    KindEditor.ready(function(K) {
        K.create('textarea[name="content"]', {
            //个性化定制内容,更多内容参数官方文档
            width: 800,
            height: 600,
            uploadJson: '/admin/upload/kindeditor',  //指定上传文件的服务器端程序,(默认值: basePath + ‘php/upload_json.php’),此处通过urls.py映射到指定程序
        });
    });
    

    4.4在文章模型管理器ArticleAdmin中添加富文本编辑器

    # Article模型管理器
    @admin.register(Article)
    class ArticleAdmin(admin.ModelAdmin):
        exclude = ('id', 'slug', 'publish')
        list_display = ('title', 'slug', 'hits', 'is_recommend', 'publish', 'category')
        filter_horizontal = ('tag',)
        list_editable = ('hits', 'is_recommend',)
        list_filter = ('category',)
        date_hierarchy = 'publish'
    
        # 将指定的静态素材应用于当前表单中
        class Media:
            js = (
                '/static/blog/js/kindeditor-4.1.11-zh-CN/kindeditor-all-min.js',
                '/static/blog/js/kindeditor-4.1.11-zh-CN/config.js',
                '/static/blog/js/kindeditor-4.1.11-zh-CN/lang/zh-CN.js',
            )
    

    4.5设置ImageFieldFileField等的上传功能路径

    1)在xdsite/settings.py中添加

    # 媒体文件配置
    MEDIA_URL = '/uploads/'
    MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
    
    # 允许上传文件类型['jpg', 'png', 'jpeg']
    ALLOW_SUFFIX = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'txt', 'html']
    

    2)在项目URL文件xdsite/urls.py中添加上传路径路由

    from django.conf.urls import url, include
    from django.contrib import admin
    from django.views import static
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^', include('blog.urls', namespace='blog', app_name='blog')),
        url(r'^uploads/(?P<path>.*)$', static.serve, {"document_root": settings.MEDIA_ROOT}),
    ]
    

    4.6在应用目录下添加kindeditor文件上传(含图片)的函数文件blog/uploads.py

    # coding: utf-8
    from django.http import HttpResponse
    from django.conf import settings
    from django.views.decorators.csrf import csrf_exempt
    import os
    import uuid
    import json
    import datetime as dt
    
    @csrf_exempt
    def upload_image(request, dir_name):
        ##################
        #  kindeditor图片上传返回数据格式说明:
        # {"error": 1, "message": "出错信息"}
        # {"error": 0, "url": "图片地址"}
        ##################
        result = {"error": 1, "message": "上传出错"}
        files = request.FILES.get("imgFile", None)
        if files:
            result = image_upload(files, dir_name)
        return HttpResponse(json.dumps(result), content_type="application/json")
    
    # 目录创建(/MEDIA_ROOT/年/月/)
    def upload_generation_dir(dir_name):
        today = dt.datetime.today()
        dir_name = dir_name + '/{0}/{1}/'.format(today.year, today.month)
        if not os.path.exists(settings.MEDIA_ROOT + dir_name):
            os.makedirs(settings.MEDIA_ROOT + dir_name)
        return dir_name
    
    # 图片上传
    def image_upload(files, dir_name):
        # 允许上传文件类型
        allow_suffix = settings.ALLOW_SUFFIX
        if allow_suffix is None:
            allow_suffix = ['jpg', 'jpeg', 'png', 'gif', 'bmp']
        file_suffix = files.name.split(".")[-1]
        if file_suffix not in allow_suffix:
            return {"error": 1, "message": "图片格式不正确"}
        relative_path_file = upload_generation_dir(dir_name)
        path = os.path.join(settings.MEDIA_ROOT, relative_path_file)
        if not os.path.exists(path):  # 如果目录不存在创建目录
            os.makedirs(path)
        file_name = str(uuid.uuid1()) + "." + file_suffix
        path_file = os.path.join(path, file_name)
        file_url = settings.MEDIA_URL + relative_path_file + file_name
        open(path_file, 'wb').write(files.file.read())
        return {"error": 0, "url": file_url}
    

    5、重启项目后登录后台进行测试

    5.1显示新注册的各个数据模块

    5.2添加文章中富文本编辑器

    5.3检查上传目录是否已经上传文件


    代码查看:https://github.com/xdao07/xdsite/tree/v0.0.3

    代码下载:git clone --branch v0.0.3 https://github.com/xdao07/xdsite.git