• Django REST framework+Vue 打造生鲜超市(三)


    四、xadmin后台管理

    4.1.xadmin添加富文本插件

    (1)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  = '<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)把插件添加到__init__.py里面

    # xadmin/plugins/__init__.py
    
    PLUGINS = (
        'ueditor',
    )

    4.2.url配置

    配置xadmin和ueditor的路由

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

    4.3.注册app到xadmin后台

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

    (1)users/adminx.py

    复制代码
    # 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)
    复制代码

    修改app名字为中文

    复制代码
    # users/apps.py
    
    from django.apps import AppConfig
    
    
    class UsersConfig(AppConfig):
        name = 'users'
        #app名字后台显示中文
        verbose_name = "用户管理"
    复制代码

    还需要__init__.py中修改默认配置才生效

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

    其它三个app一样的操作

    (2)goods/adminx.py

    复制代码
    # 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'

    (3)trade/adminx.py

    复制代码
    # 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'

    (4)user_operation/adminx.py

    复制代码
    # 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'

    (5)生成数据库表

    python manage.py makemigrations
    
    python manage.py migrate

    4.4.导入商品类别数据

    由于分类和商品很多,就写个脚本导入数据

    单独使用django的model,批量导入数据

    • db_tools下新建文件夹data,然后把前端的json文件(category_data和product_data)拷贝到里面
    •  把brands和goods图片拷贝到media目录下

    db_tools下新建文件 import_category_data.py

    代码如下:

    复制代码
    # db_tools/data/import_category_data.py
    
    #独立使用django的model
    import sys
    import os
    
    #获取当前文件的路径(运行脚本)
    pwd = os.path.dirname(os.path.realpath(__file__))
    #获取项目的跟目录
    sys.path.append(pwd+"../")
    #要想单独使用django的model,必须指定一个环境变量,会去settings配置找
    #参照manage.py里面就知道为什么这样设置了
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MxShop.settings")
    
    import django
    django.setup()
    
    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()
    复制代码

    然后运行脚本 import_category_data.py  数据就可以保存到数据库了

    4.5.导入商品

     在data目录下新建import_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()
    复制代码

    然后运行,把商品生产到数据库中

    配置media路径

    settings中

    # 设置上传文件的路径
    MEDIA_URL="/media/"
    MEDIA_ROOT=os.path.join(BASE_DIR,"media")

    urls.py

    复制代码
    # MxShop/urls.py
    __author__ = 'derek'
    
    from django.urls import path,include
    import xadmin
    from django.views.static import serve
    from MxShop.settings import MEDIA_ROOT
    
    urlpatterns = [
        path('xadmin/', xadmin.site.urls),
        path('ueditor/',include('DjangoUeditor.urls' )),
        #文件
        path('media/<path:path>',serve,{'document_root':MEDIA_ROOT}),
    ]
    复制代码

     目录结构

  • 相关阅读:
    HP LoadRunner11.0下载地址(官网地址)
    出现500错误[code=CANT_CONNECT_LOOPBACK] Cannot connect due to potential loopback problems的解决方法
    一个数据库的所见即所得的好工具
    强制释放windows被占用的端口
    测试管理工具QC第二篇QC安装步骤(史上最详细的图解过程)第二篇server2003的环境设置
    NAT连接虚拟机和主机的通信(静态IP配置完整图解,测试通过可用)附vmware tools的安装(未完待续)第一篇
    QC插件大集合
    winmail搭建自己的邮件服务器第二篇(详细图解,测试通过)
    QTP基本脚本设计(第一部分)
    winmail搭建自己的邮件服务器第一篇(附详细图解测试通过可用)
  • 原文地址:https://www.cnblogs.com/daluozi/p/9467326.html
Copyright © 2020-2023  润新知