(项目)生鲜超市
Posted sweltering
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了(项目)生鲜超市相关的知识,希望对你有一定的参考价值。
四、xadmin后台管理
1、xadmin添加富文本插件
在xadmin/plugins文件下面新建文件ueditor.py,添加如下代码:
1 import xadmin 2 from xadmin.views import BaseAdminPlugin, CreateAdminView, ModelFormAdminView, UpdateAdminView 3 from DjangoUeditor.models import UEditorField 4 from DjangoUeditor.widgets import UEditorWidget 5 from django.conf import settings 6 7 8 class XadminUEditorWidget(UEditorWidget): 9 def __init__(self, **kwargs): 10 self.ueditor_options = kwargs 11 self.Media.js = None 12 super(XadminUEditorWidget, self).__init__(kwargs) 13 14 15 class UeditorPlugin(BaseAdminPlugin): 16 17 def get_field_style(self, attrs, db_field, style, **kwargs): 18 if style == ‘ueditor‘: 19 if isinstance(db_field, UEditorField): 20 widget = db_field.formfield().widget 21 param = {} 22 param.update(widget.ueditor_settings) 23 param.update(widget.attrs) 24 return {‘widget‘: XadminUEditorWidget(**param)} 25 return attrs 26 27 def block_extrahead(self, context, nodes): 28 js = ‘<script type="text/javascript" src="%s"></script>‘ % (settings.STATIC_URL + "ueditor/ueditor.config.js") 29 js += ‘<script type="text/javascript" src="%s"></script>‘ % (settings.STATIC_URL + "ueditor/ueditor.all.min.js") 30 nodes.append(js) 31 32 33 xadmin.site.register_plugin(UeditorPlugin, UpdateAdminView) 34 xadmin.site.register_plugin(UeditorPlugin, CreateAdminView)
然后将插件添加到__init__.py中:
1 PLUGINS = ( 2 ‘ueditor‘ 3 )
然后配置xadmin和ueditor的路由:
1 from django.urls import path, include 2 import xadmin 3 4 urlpatterns = [ 5 path(‘xadmin/‘, xadmin.site.urls), 6 path(‘ueditor/‘, include(‘DjangoUeditor.urls‘)), 7 ]
2、在xadmin后台注册model
首先在四个app先都新建adminx.py文件,分别进行注册。
xadmin的使用在线教育平台中有详细介绍,这里不再赘述。
2.1 用户model注册
1 import xadmin 2 from xadmin import views 3 4 from .models import VerifyCode 5 6 class BaseSetting(object): 7 """基础配置""" 8 9 # 添加主题功能 10 enable_themes = True 11 use_bootswatch = True 12 13 14 class GlobalSettings(object): 15 """全局配置""" 16 17 site_title = ‘倍思乐超市后台管理系统‘ 18 site_footer = ‘https://www.cnblogs.com/Sweltering/‘ 19 menu_style = ‘accordion‘ 20 21 22 class VerifyCodeAdmin(object): 23 list_display = [‘code‘, ‘mobile‘, "add_time"] 24 25 26 xadmin.site.register(VerifyCode, VerifyCodeAdmin) 27 xadmin.site.register(views.BaseAdminView, BaseSetting) 28 xadmin.site.register(views.CommAdminView, GlobalSettings)
要想后台中app的名字是中文显示,需要在apps.py中添加:
1 from django.apps import AppConfig 2 3 4 class UsersConfig(AppConfig): 5 name = ‘users‘ 6 verbose_name = ‘用户管理‘
然后在__init__.py中添加:
1 default_app_config = ‘users.apps.UsersConfig‘
2.2 商品model注册
1 import xadmin 2 from .models import Goods, GoodsCategory, GoodsImage, GoodsCategoryBrand, Banner, HotSearchWords 3 from .models import IndexAd 4 5 6 class GoodsAdmin(object): 7 list_display = ["name", "click_num", "sold_num", "fav_num", "goods_num", "market_price", 8 "shop_price", "goods_brief", "goods_desc", "is_new", "is_hot", "add_time"] 9 search_fields = [‘name‘, ] 10 list_editable = ["is_hot", ] 11 list_filter = ["name", "click_num", "sold_num", "fav_num", "goods_num", "market_price", 12 "shop_price", "is_new", "is_hot", "add_time", "category__name"] 13 style_fields = {"goods_desc": "ueditor"} 14 15 # 在添加商品的时候可以添加商品图片 16 class GoodsImagesInline(object): 17 model = GoodsImage 18 exclude = ["add_time"] 19 extra = 1 20 style = ‘tab‘ 21 22 inlines = [GoodsImagesInline] 23 24 25 class GoodsCategoryAdmin(object): 26 list_display = ["name", "category_type", "parent_category", "add_time"] 27 list_filter = ["category_type", "parent_category", "name"] 28 search_fields = [‘name‘, ] 29 30 31 class GoodsBrandAdmin(object): 32 list_display = ["category", "image", "name", "desc"] 33 34 def get_context(self): 35 context = super(GoodsBrandAdmin, self).get_context() 36 if ‘form‘ in context: 37 context[‘form‘].fields[‘category‘].queryset = GoodsCategory.objects.filter(category_type=1) 38 return context 39 40 41 class BannerGoodsAdmin(object): 42 list_display = ["goods", "image", "index"] 43 44 45 class HotSearchAdmin(object): 46 list_display = ["keywords", "index", "add_time"] 47 48 49 class IndexAdAdmin(object): 50 list_display = ["category", "goods"] 51 52 53 xadmin.site.register(Goods, GoodsAdmin) 54 xadmin.site.register(GoodsCategory, GoodsCategoryAdmin) 55 xadmin.site.register(Banner, BannerGoodsAdmin) 56 xadmin.site.register(GoodsCategoryBrand, GoodsBrandAdmin) 57 xadmin.site.register(HotSearchWords, HotSearchAdmin) 58 xadmin.site.register(IndexAd, IndexAdAdmin)
在apps.py中配置:
1 from django.apps import AppConfig 2 3 4 class GoodsConfig(AppConfig): 5 name = ‘goods‘ 6 verbose_name = ‘商品管理‘
在__init__.py中配置:
1 default_app_config = ‘goods.apps.GoodsConfig‘
2.3 交易的model注册
1 import xadmin 2 from .models import ShoppingCart, OrderInfo, OrderGoods 3 4 5 class ShoppingCartAdmin(object): 6 list_display = ["user", "goods", "nums", ] 7 8 9 class OrderInfoAdmin(object): 10 list_display = ["user", "order_sn", "trade_no", "pay_status", "post_script", "order_mount", 11 "order_mount", "pay_time", "add_time"] 12 13 class OrderGoodsInline(object): 14 model = OrderGoods 15 exclude = [‘add_time‘, ] 16 extra = 1 17 style = ‘tab‘ 18 19 inlines = [OrderGoodsInline, ] 20 21 22 xadmin.site.register(ShoppingCart, ShoppingCartAdmin) 23 xadmin.site.register(OrderInfo, OrderInfoAdmin)
在apps.py中配置:
1 from django.apps import AppConfig 2 3 4 class TradeConfig(AppConfig): 5 name = ‘trade‘ 6 verbose_name = ‘交易管理‘
在__init__.py中配置:
1 default_app_config = ‘trade.apps.TradeConfig‘
2.4 用户操作的model注册
1 import xadmin 2 from .models import UserFav, UserLeavingMessage, UserAddress 3 4 5 class UserFavAdmin(object): 6 list_display = [‘user‘, ‘goods‘, "add_time"] 7 8 9 class UserLeavingMessageAdmin(object): 10 list_display = [‘user‘, ‘message_type‘, "message", "add_time"] 11 12 13 class UserAddressAdmin(object): 14 list_display = ["signer_name", "signer_mobile", "district", "address"] 15 16 17 xadmin.site.register(UserFav, UserFavAdmin) 18 xadmin.site.register(UserAddress, UserAddressAdmin) 19 xadmin.site.register(UserLeavingMessage, UserLeavingMessageAdmin)
在apps.py中配置:
1 from django.apps import AppConfig 2 3 4 class UserOperationConfig(AppConfig): 5 name = ‘user_operation‘ 6 verbose_name = ‘用户操作管理‘
在__init__.py中配置:
1 default_app_config = ‘user_operation.apps.UserOperationConfig‘
至此,所有的model注册完毕,之前也将每个app的model设计好了,现在直接迁移生成数据库中的表。
3、导入商品数据
由于该项目的数据较多,直接写个脚本导入数据。
在db_tools下面新建文件夹data,然后将前端的json数据文件(category_data和product_data)拷贝到该文件夹下面,然后将brands和goods图片拷贝到media目录下:
然后在db_tools下新建脚本文件import_category_data.py导入类别数据:
1 # db_tools/data/import_category_data.py 2 3 # 独立使用django的model 4 import sys 5 import os 6 7 # 获取当前文件的路径(运行脚本) 8 pwd = os.path.dirname(os.path.realpath(__file__)) 9 # 获取项目的跟目录 10 sys.path.append(pwd + "../") 11 # 要想单独使用django的model,必须指定一个环境变量,会去settings配置找 12 # 参照manage.py里面就知道为什么这样设置了 13 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MxShop.settings") 14 15 import django 16 17 django.setup() 18 19 from goods.models import GoodsCategory 20 21 from db_tools.data.category_data import row_data 22 23 # 一级类 24 for lev1_cat in row_data: 25 lev1_intance = GoodsCategory() 26 lev1_intance.code = lev1_cat["code"] 27 lev1_intance.name = lev1_cat["name"] 28 lev1_intance.category_type = 1 29 # 保存到数据库 30 lev1_intance.save() 31 # 二级类 32 for lev2_cat in lev1_cat["sub_categorys"]: 33 lev2_intance = GoodsCategory() 34 lev2_intance.code = lev2_cat["code"] 35 lev2_intance.name = lev2_cat["name"] 36 lev2_intance.category_type = 2 37 lev2_intance.parent_category = lev1_intance 38 lev2_intance.save() 39 # 三级类 40 for lev3_cat in lev2_cat["sub_categorys"]: 41 lev3_intance = GoodsCategory() 42 lev3_intance.code = lev3_cat["code"] 43 lev3_intance.name = lev3_cat["name"] 44 lev3_intance.category_type = 3 45 lev3_intance.parent_category = lev2_intance 46 lev3_intance.save()
直接运行该py文件即可将数据导入数据库:
在db_tools下新建脚本文件import_goods_data.py导入商品数据:
1 import sys 2 import os 3 4 pwd = os.path.dirname(os.path.realpath(__file__)) 5 sys.path.append(pwd + "../") 6 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MxShop.settings") 7 8 import django 9 10 django.setup() 11 12 from goods.models import Goods, GoodsCategory, GoodsImage 13 14 from db_tools.data.product_data import row_data 15 16 for goods_detail in row_data: 17 goods = Goods() 18 goods.name = goods_detail["name"] 19 # 前端中是“¥232”,数据库中是float类型,所以要替换掉 20 goods.market_price = float(int(goods_detail["market_price"].replace("¥", "").replace("元", ""))) 21 goods.shop_price = float(int(goods_detail["sale_price"].replace("¥", "").replace("元", ""))) 22 goods.goods_brief = goods_detail["desc"] if goods_detail["desc"] is not None else "" 23 goods.goods_desc = goods_detail["goods_desc"] if goods_detail["goods_desc"] is not None else "" 24 # 取第一张作为封面图 25 goods.goods_front_image = goods_detail["images"][0] if goods_detail["images"] else "" 26 # 取最后一个 27 category_name = goods_detail["categorys"][-1] 28 # 取出当前子类对应的GoodsCategory对象,filter没有匹配的会返回空数组,不会抛异常。 29 category = GoodsCategory.objects.filter(name=category_name) 30 if category: 31 goods.category = category[0] 32 goods.save() 33 34 for goods_image in goods_detail["images"]: 35 goods_image_instance = GoodsImage() 36 goods_image_instance.image = goods_image 37 goods_image_instance.goods = goods 38 goods_image_instance.save()
直接执行该脚本,即可将数据导入数据库:
以上是关于(项目)生鲜超市的主要内容,如果未能解决你的问题,请参考以下文章