• 【Vue+DRF 生鲜电商】xadmin 后台管理(二)


    1. xadmin 添加富文本插件

    xadmin 中添加插件,使其能够支持富文本。

    1、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 = '<script type="text/javascript" src="%s"></script>' % (settings.STATIC_URL + "ueditor/ueditor.config.js")
            js += '<script type="text/javascript" src="%s"></script>' % (settings.STATIC_URL + "ueditor/ueditor.all.min.js")
            nodes.append(js)
    
    
    xadmin.site.register_plugin(UeditorPlugin, UpdateAdminView)
    xadmin.site.register_plugin(UeditorPlugin, CreateAdminView)
    

    2、将插件添加到 xadmin/plugins/__init__.py

    PLUGINS = (
        'actions',
        'filters',
        ...    
    
        'ueditor',
    )
    

    2. 配置 xadmin 后台

    2.1 用户 users

    1、新建 apps/users/adminx.py

    import xadmin
    from xadmin import views
    from .models import VerifyCord
    
    
    class BaseSetting(object):
        """添加主题功能"""
        enable_themes = True
        use_bootswatch = True
    
    
    class GlobalSetting(object):
        """全局配置,后台管理标题和页脚"""
        site_title = 'Hubery_Jun'
        site_footer = 'https://www.bilibili.com'
        menu_style = 'accordion'  # 菜单收缩
    
    
    class VerifyCodeAdmin(object):
        list_display = ['code', 'mobile', 'add_time']
    
    
    xadmin.site.register(VerifyCord, VerifyCodeAdmin)
    xadmin.site.register(views.BaseAdminView, BaseSetting)
    xadmin.site.register(views.CommAdminView, GlobalSetting)
    

    2、修改 app 名称为中文 users/apps.py

    from django.apps import AppConfig
    
    
    class UsersConfig(AppConfig):
        name = 'users'
    
        # 设置 app 名字为中文,admin 中
        verbose_name = '用户管理'
    

    3、修改默认配置 users/__init__.py

    default_app_config = 'users.apps.UsersConfig'
    

    其他三个 APP 配置类似。

    2.2 商品 goods

    1、新建 apps/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)
    

    2、修改 app 名称为中文 goods/apps.py

    from django.apps import AppConfig
    
    
    class UsersConfig(AppConfig):
        name = 'goods'
    
        # 设置 app 名字为中文,admin 中
        verbose_name = '商品管理'
    

    3、修改默认配置 goods/__init__.py

    default_app_config = 'goods.apps.GoodsConfig'
    

    2.3 交易 trade

    1、新建 apps/trade/adminx.py

    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)
    

    2、修改 app 名称为中文 trade/apps.py

    from django.apps import AppConfig
    
    
    class UsersConfig(AppConfig):
        name = 'trade'
    
        # 设置 app 名字为中文,admin 中
        verbose_name = '交易管理'
    

    3、修改默认配置 trade/__init__.py

    default_app_config = 'trade.apps.TradeConfig'
    

    2.4 用户操作 user_operation

    1、新建 apps/user_operation/adminx.py

    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)
    

    2、修改 app 名称为中文 user_operation/apps.py

    from django.apps import AppConfig
    
    
    class UsersConfig(AppConfig):
        name = 'user_operation'
    
        # 设置 app 名字为中文,admin 中
        verbose_name = '操作管理'
    

    3、修改默认配置 user_operation/__init__.py

    default_app_config = 'user_operation.apps.UserOperationConfig'
    

    3. 导入数据

    db_tools 下新建目录 data,将 category_data.py 和product_data.py 拷贝到目录中。另外将相关图片拷贝到 media 目录中。

    3.1 导入分类信息

    新建 db_tools/import_category_data.py

    # 独立使用django的model
    import sys
    import os
    
    #  获取当前文件的路径,以及路径的父级文件夹名
    pwd = os.path.dirname(os.path.realpath(__file__))
    # 将项目目录加入setting
    sys.path.append(pwd + "../")
    # manage.py中
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MxShop.settings")
    
    import django
    
    django.setup()
    
    # 这行代码必须在初始化django之后
    from goods.models import GoodsCategory
    
    from db_tools.data.category_data import row_data
    
    # 一级分类
    for lev1_cat in row_data:
        lev1_intance = GoodsCategory()
        lev1_intance.code = lev1_cat["code"]
        lev1_intance.name = lev1_cat["name"]
        lev1_intance.category_type = 1
        lev1_intance.save()
    
        # 二级分类
        for lev2_cat in lev1_cat["sub_categorys"]:
            lev2_intance = GoodsCategory()
            lev2_intance.code = lev2_cat["code"]
            lev2_intance.name = lev2_cat["name"]
            lev2_intance.category_type = 2
            lev2_intance.parent_category = lev1_intance
            lev2_intance.save()
    
            # 三级分类
            for lev3_cat in lev2_cat["sub_categorys"]:
                lev3_intance = GoodsCategory()
                lev3_intance.code = lev3_cat["code"]
                lev3_intance.name = lev3_cat["name"]
                lev3_intance.category_type = 3
                lev3_intance.parent_category = lev2_intance
                lev3_intance.save()
    

    3.2 导入商品信息

    新建 db_toolsimport_goods_data.py

    import sys
    import os
    
    pwd = os.path.dirname(os.path.realpath(__file__))
    sys.path.append(pwd+"../")
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MxShop.settings")
    
    import django
    django.setup()
    
    from goods.models import Goods, GoodsCategory, GoodsImage
    
    from db_tools.data.product_data import row_data
    
    for goods_detail in row_data:
        goods = Goods()
        goods.name = goods_detail["name"]
        #前端中是“¥232”,数据库中是float类型,所以要替换掉
        goods.market_price = float(int(goods_detail["market_price"].replace("¥", "").replace("元", "")))
        goods.shop_price = float(int(goods_detail["sale_price"].replace("¥", "").replace("元", "")))
        goods.goods_brief = goods_detail["desc"] if goods_detail["desc"] is not None else ""
        goods.goods_desc = goods_detail["goods_desc"] if goods_detail["goods_desc"] is not None else ""
        # 取第一张作为封面图
        goods.goods_front_image = goods_detail["images"][0] if goods_detail["images"] else ""
        #取最后一个
        category_name = goods_detail["categorys"][-1]
        # 取出当前子类对应的GoodsCategory对象,filter没有匹配的会返回空数组,不会抛异常。
        category = GoodsCategory.objects.filter(name=category_name)
        if category:
            goods.category = category[0]
        goods.save()
    
        for goods_image in goods_detail["images"]:
            goods_image_instance = GoodsImage()
            goods_image_instance.image = goods_image
            goods_image_instance.goods = goods
            goods_image_instance.save()
    

    运行项目,访问 http://127.0.0.1:8000/xadmin/ 即可进行后台管理。

  • 相关阅读:
    linux网络编程之socket编程(三)
    linux网络编程之socket编程(二)
    字符串转成时间戳
    xls的读写
    统计词语频率保存到xls
    信息时代的学习(对于人类)
    编码格式简介:ASCII码、ANSI、GBK、GB2312、GB18030和Unicode、UTF-8,BOM头
    ThinkPHP中:RBAC权限控制的实习步骤
    getField()和select()方法的区别
    按钮美化,变化显示效果
  • 原文地址:https://www.cnblogs.com/midworld/p/13629672.html
Copyright © 2020-2023  润新知