1. 程式人生 > >(項目)生鮮超市(三)

(項目)生鮮超市(三)

ping front 交易 blog 顯示 替換 sim tde .get

四、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()

  直接執行該腳本,即可將數據導入數據庫:

技術分享圖片

(項目)生鮮超市(三)