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}),
]

目录结构

原文地址:https://www.cnblogs.com/daluozi/p/9467326.html

时间: 2024-10-10 16:54:01

Django REST framework+Vue 打造生鲜超市(三)的相关文章

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

一.项目介绍 1.1.掌握的技术 Vue + Django Rest Framework 前后端分离技术 彻底玩转restful api 开发流程 Django Rest Framework 的功能实现和核心源码分析 Sentry 完成线上系统的错误日志的监控和告警 第三方登录和支付宝支付的集成 本地调试远程服务器代码的技巧 1.2.课程系统构成 vue前端项目 django rest framework 系统实现前台功能 xadmin后台管理系统 vue部分: API 接口 Vue 组件 与a

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

六.商品类别数据展示 6.1. 商品类别数据接口 (1)商品分类有两个接口: 一种是全部分类:一级二级三级 一种是某一类的分类以及商品详细信息: 开始写商品分类的接口 (2)序列化 给分类添加三级分类的serializer goods/serializers.py from rest_framework import serializers from .models import Goods,GoodsCategory class CategorySerializer3(serializers.

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

三.Models设计 3.1.项目初始化 (1)进虚拟环境下安装 django2.0.2 djangorestframework和相关依赖mark,filter pillow  图片处理 pip install djangorestframework pip install -i https://pypi.douban.com/simple django==2.0.2 pip install markdown pip install django-filter pip install pillo

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

十.购物车.订单管理和支付功能 10.1.添加商品到购物车 (1)trade/serializer.py # trade/serializer.py __author__ = 'derek' from .models import ShoppingCart from rest_framework import serializers from goods.models import Goods class ShopCartSerializer(serializers.Serializer): #

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

十四.social_django 集成第三方登录 14.1.申请应用 进入微博开放平台,首先要经过认证,然后才可以创建应用 地址:http://open.weibo.com/authentication 创建应用 写上应用的名字,创建好后,会有个“App Key”,这个非常重要  OAuth2.0 授权设置 正常情况下,必须经过审核才可以让第三方登录,我们可以先用测试模式来完成. (1)添加测试用户,可以测试登录 (2)高级信息  14.2.第三方登录 我们用social_django第三方库来

3- vue django restful framework 打造生鲜超市 - model设计和资源导入

3- vue django restful framework 打造生鲜超市 - model设计和资源导入 使用Python3.6与Django2.0.2(Django-rest-framework)以及前端vue开发的前后端分离的商城网站 项目支持支付宝支付(暂不支持微信支付),支持手机短信验证码注册, 支持第三方登录.集成了sentry错误监控系统. 本小节内容: model设计与资源引入 资源初始化 数据库设计,数据表结构 新建虚拟环境 mkvirtualenv -p=D:\softEnv

Django rest framework + Vue简单示例

一.创建Vue项目 修改源:npm config set registry https://registry.npm.taobao.org         (建议修改) 创建脚手架:vue init webpack Vue项目名称 基本插件: axios,发送Ajax请求 vuex,保存所有组件共用的变量 vue-cookies,操作cookie 二.流程 vue项目基本目录结构 1.创建脚手架 vue init webpack Vue项目名称 运行 npm run dev 2.App.Vue中

Django Rest framework序列化流程

目录 一 什么是序列化 二 Django REST framework配置流程之Serializer 三 Django REST framework配置流程之ModelSerializer 一 什么是序列化 序列化模型与序列化关系模型 序列化模型,顾名思义,即对 models 里的数据模型作序列化. 而序列化关系模型则是对 models 里数据模型中带有关系的如 ForeignKey, ManyToManyField 和 OneToOneField 字段作序列化. Django Rest Fra

引爆潮流技术 Vue+Django REST framework打造生鲜电商项目

引爆潮流技术Vue+Django REST framework打造生鲜电商项目 1.Django REST framework框架介绍 Django REST framework框架是一个功能强大且灵活的工具包,用于构建Web API,且Django Rest Framework 是 Django 依赖扩展 Restful Api 的框架,与Django的使用风格类似,它的官方网站是:https://www.django-rest-framework.org/ 2.设计API 我们先选择一个AP