14.Django-xadmin和富文本编辑器

xadmin

安装&配置

https://github.com/sshwsfc/xadmin

  • 选择django2 进行下载,不要下载主分支
    14.Django-xadmin和富文本编辑器_第1张图片
  • 切换到虚拟环境进行安装
    # pip install 本地路径+文件名
    pip install G:\Downloads\chrome\xadmin-django2.zip
    
  • 为了方便对xadmin源码进行修改操作,所以可以直接将下载好的xadmin-master.zip包进行解压后,在解压的文件中 找xadmin文件拷贝到项目根目录下的extra_apps包下(需要创建extra_apps包),该操作为源码安装

14.Django-xadmin和富文本编辑器_第2张图片

14.Django-xadmin和富文本编辑器_第3张图片

  • 把extra_apps右键mark为Source Root

14.Django-xadmin和富文本编辑器_第4张图片

  • settings中加入extra_apps的路径并注册

    # settings.py
    import sys
    sys.path.insert(0,os.path.join(BASE_DIR, 'extra_apps'))
    
    INSTALLED_APPS = [
        ''''''
        'xadmin',
        'crispy_forms',
    ]
    
  • 配置路由

    # urls.py
    from django.urls import path
    import xadmin
    urlpatterns = [
        path('xadmin/', xadmin.site.urls),
    ]
    
  • 设置成中文

    LANGUAGE_CODE = 'zh-hans'
    TIME_ZONE = 'Asia/Shanghai'
    USE_I18N = True
    USE_L10N = True
    USE_TZ = False
    

xadmin添加富文本插件

  • xadmin/plugins文件夹下新建文件ueditor.py

    # xadmin/plugins/ueditor.py
    
    import xadmin
    from xadmin.views import BaseAdminPlugin, CreateAdminView, ModelFormAdminView, UpdateAdminView
    from DjangoUeditor.models import UEditorField
    from DjangoUeditor.widgets import UEditorWidget
    from django.conf import settings
    
    class XadminUEditorWidget(UEditorWidget):
        def __init__(self, **kwargs):
            self.ueditor_options = kwargs
            self.Media.js = None
            super(XadminUEditorWidget,self).__init__(kwargs)
    
    class UeditorPlugin(BaseAdminPlugin):
        def get_field_style(self, attrs, db_field, style, **kwargs):
            if style == 'ueditor':
                if isinstance(db_field, UEditorField):
                    widget = db_field.formfield().widget
                    param = {}
                    param.update(widget.ueditor_settings)
                    param.update(widget.attrs)
                    return {'widget':XadminUEditorWidget(**param)}
            return attrs
    
        def block_extrahead(self, context, nodes):
            js  = '' %(settings.STATIC_URL + "ueditor/ueditor.config.js")
            js += '' %(settings.STATIC_URL + "ueditor/ueditor.all.min.js")
            nodes.append(js)
    
    xadmin.site.register_plugin(UeditorPlugin, UpdateAdminView)
    xadmin.site.register_plugin(UeditorPlugin, CreateAdminView)
    
  • 把插件添加到__init__.py里面

    # xadmin/plugins/__init__.py
    PLUGINS = ('actions','filters','bookmark','export','layout','refresh','details','editable','relate','chart','ajax','relfield','inline','topnav','portal','quickform','wizard','images','auth','multiselect','themes','aggregation','mobile','passwords','sitemenu','language','quickfilter','sortablelist','importexport','ueditor',)
    
  • 配置ueditor的路由

    # MxShop/urls.py
    import xadmin
    from django.urls import path,include
    
    urlpatterns = [
        path('xadmin/', xadmin.site.urls),
        path('ueditor/', include('DjangoUeditor.urls')),
    ]
    

注册app到xadmin后台

四个app下面都新建文件adminx.py,然后分别注册到后台

users

  1. # users/adminx.py
    __author__ = 'derek'
    
    import xadmin
    from xadmin import views
    from .models import VerifyCode
    
    
    class BaseSetting(object):
        #添加主题功能
        enable_themes = True
        use_bootswatch = True
    
    
    class GlobalSettings(object):
        #全局配置,后台管理标题和页脚
        site_title = "仙剑奇侠传"
        site_footer = "http://www.cnblogs.com/derek1184405959/"
        #菜单收缩
        menu_style = "accordion"
    
    
    class VerifyCodeAdmin(object):
        list_display = ['code', 'mobile', "add_time"]
    
    
    xadmin.site.register(VerifyCode, VerifyCodeAdmin)
    xadmin.site.register(views.BaseAdminView, BaseSetting)
    xadmin.site.register(views.CommAdminView, GlobalSettings)
    
  2. 修改app名字为中文

    # users/apps.py
    from django.apps import AppConfig
    class UsersConfig(AppConfig):
        name = 'users'
        #app名字后台显示中文
        verbose_name = "用户管理"
    
  3. 还需要__init__.py中修改默认配置才生效

    # users/__init__.py
    default_app_config = 'users.apps.UsersConfig'
    

goods

  1. # goods/adminx.py
    
    import xadmin
    from .models import Goods, GoodsCategory, GoodsImage, GoodsCategoryBrand, Banner, HotSearchWords
    from .models import IndexAd
    
    class GoodsAdmin(object):
        #显示的列
        list_display = ["name", "click_num", "sold_num", "fav_num", "goods_num", "market_price",
                        "shop_price", "goods_brief", "goods_desc", "is_new", "is_hot", "add_time"]
        #可以搜索的字段
        search_fields = ['name', ]
        #列表页可以直接编辑的
        list_editable = ["is_hot", ]
        #过滤器
        list_filter = ["name", "click_num", "sold_num", "fav_num", "goods_num", "market_price",
                       "shop_price", "is_new", "is_hot", "add_time", "category__name"]
        #富文本编辑器
        style_fields = {"goods_desc": "ueditor"}
    
        #在添加商品的时候可以添加商品图片
        class GoodsImagesInline(object):
            model = GoodsImage
            exclude = ["add_time"]
            extra = 1
            style = 'tab'
    
        inlines = [GoodsImagesInline]
    
    class GoodsCategoryAdmin(object):
        list_display = ["name", "category_type", "parent_category", "add_time"]
        list_filter = ["category_type", "parent_category", "name"]
        search_fields = ['name', ]
    
    class GoodsBrandAdmin(object):
        list_display = ["category", "image", "name", "desc"]
    
        def get_context(self):
            context = super(GoodsBrandAdmin, self).get_context()
            if 'form' in context:
                context['form'].fields['category'].queryset = GoodsCategory.objects.filter(category_type=1)
            return context
    
    class BannerGoodsAdmin(object):
        list_display = ["goods", "image", "index"]
    
    class HotSearchAdmin(object):
        list_display = ["keywords", "index", "add_time"]
    
    class IndexAdAdmin(object):
        list_display = ["category", "goods"]
    
    xadmin.site.register(Goods, GoodsAdmin)
    xadmin.site.register(GoodsCategory, GoodsCategoryAdmin)
    xadmin.site.register(Banner, BannerGoodsAdmin)
    xadmin.site.register(GoodsCategoryBrand, GoodsBrandAdmin)
    
    xadmin.site.register(HotSearchWords, HotSearchAdmin)
    xadmin.site.register(IndexAd, IndexAdAdmin)
    
    # goods/apps.py
    from django.apps import AppConfig
    class GoodsConfig(AppConfig):
        name = 'goods'
        verbose_name = '商品管理'
    
    # good/__init__.py
    default_app_config = 'goods.apps.GoodsConfig'
    

trade

  1. # trade/adminx.py
    __author__ = 'derek'
    
    import xadmin
    from .models import ShoppingCart, OrderInfo, OrderGoods
    
    class ShoppingCartAdmin(object):
        list_display = ["user", "goods", "nums", ]
    
    class OrderInfoAdmin(object):
        list_display = ["user", "order_sn",  "trade_no", "pay_status", "post_script", "order_mount",
                        "order_mount", "pay_time", "add_time"]
    
        class OrderGoodsInline(object):
            model = OrderGoods
            exclude = ['add_time', ]
            extra = 1
            style = 'tab'
    
        inlines = [OrderGoodsInline, ]
    
    xadmin.site.register(ShoppingCart, ShoppingCartAdmin)
    xadmin.site.register(OrderInfo, OrderInfoAdmin)
    
    # trade/apps.py
    from django.apps import AppConfig
    class TradeConfig(AppConfig):
        name = 'trade'
        verbose_name = '交易管理'
    
    # trade/__init__.py
    default_app_config = 'trade.apps.TradeConfig'
    

user_operation

  1. # user_operation/adminx.py
    __author__ = 'derek'
    
    import xadmin
    from .models import UserFav, UserLeavingMessage, UserAddress
    
    class UserFavAdmin(object):
        list_display = ['user', 'goods', "add_time"]
    
    class UserLeavingMessageAdmin(object):
        list_display = ['user', 'message_type', "message", "add_time"]
    
    
    class UserAddressAdmin(object):
        list_display = ["signer_name", "signer_mobile", "district", "address"]
    
    xadmin.site.register(UserFav, UserFavAdmin)
    xadmin.site.register(UserAddress, UserAddressAdmin)
    xadmin.site.register(UserLeavingMessage, UserLeavingMessageAdmin)
    
    # user_operation/apps.py
    from django.apps import AppConfig
    class UserOperationConfig(AppConfig):
        name = 'user_operation'
        verbose_name = '操作管理'
        
    # user_operation/__init__.py
    default_app_config = 'user_operation.apps.UserOperationConfig'
    

你可能感兴趣的:(14.Django-xadmin和富文本编辑器)