新人学习django 是按照这个大佬的教程学习的
链接: https://www.cnblogs.com/derek1184405959/p/8733194.html.
很多步骤都是按照上面的教程学习的,这里只是记录一下自己学习的过程和一些错误
如果有人想要系统的学习,建议去上面那位大佬处学习
1.配置url
from django.urls import path
import xadmin
from django.urls import include
urlpatterns = [
path('xadmin/', xadmin.site.urls),
path('ueditor/', include('DjangoUeditor.urls')),
]
2.注册app到xadmin后台
from django.contrib import admin
# Register your models here.
import xadmin
from xadmin import views
from xadmin.views import BaseAdminView, CommAdminView
from .models import VerifyCode
#添加主题
class BaseSetting(object):
enable_themes=True
use_bootswatch=True
#全局配置,后台管理标题和页脚
class GlobalSettings(object):
site_title="珂朵莉"
site_footer="alotria"
#菜单收缩
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名字为中文
```
from django.apps import AppConfig
class UsersConfig(AppConfig):
name = ‘apps.users’
#后台管理时显示为中文
verbosse_name=“用户管理”
还需要配置__init__.py
default_app_config="users.apps.UsersConfig"
同理分别配置goods,trade和user_operations
goods
from django.contrib import admin
import xadmin
from .models import *
from .models import IndexAd
# Register your models here.
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","category","is_new","is_hot","add_time"]
#富文本编辑器
style_fields={"goods_desc":"ueditor"}
#在添加商品的时候可以添加商品图片
class GoodsImageInline(object):
model=GoodsImage
exclude=["add_time"]
extra=1
style="tan"
inlines=[GoodsImageInline]
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 HostSearchAdmin(object):
list_display=["keywords","index","add_time"]
class IndexAdmin(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(HostSearchWords,HostSearchAdmin)
xadmin.site.register(IndexAd,IndexAdmin)
apps配置
from django.apps import AppConfig
class GoodsConfig(AppConfig):
name = 'apps.goods'
verbose_name="商品管理"
__init__.py配置
default_app_config="goods.apps.GoodsConfig"
trade
from django.contrib import admin
# Register your models here.
__author__="wtt"
import xadmin
from .models import ShoppingCar,OrderInfo,OrderGoods
class ShoppingCarAdmin(object):
list_display=["user","goods","nums"]
class OrderInfoAdmin(object):
list_display=["user","order_id","trade_on","pay_status","post_script",
"order_mount","pay_time","add_time"]
class OrderGoodsInline(object):
model=OrderGoods
exclude=["add_time",]
extra=1
style="tab"
inlines=[OrderGoodsInline,]
xadmin.site.register(ShoppingCar,ShoppingCarAdmin)
xadmin.site.register(OrderInfo,OrderInfoAdmin)
from django.apps import AppConfig
class TradeConfig(AppConfig):
name = 'apps.trade'
verbose_name="交易管理"
default_app_config="trade.apps.TradeConfig"
user_operations
from django.contrib import admin
# Register your models here.
__author__="wtt"
import xadmin
from .models import *
class UserFavAdmin(object):
list_diaplay=["user","goods","add_time"]
class UserLeavingMessageAdmin(object):
list_display=["user","message_type","message","add_time"]
class UserAddressAdmin(object):
list_display=["singer_name","singer_mobile","district","address"]
xadmin.site.register(UserFav,UserFavAdmin)
xadmin.site.register(UserAddress,UserAddressAdmin)
xadmin.site.register(UserLeavingMessage,UserLeavingMessageAdmin)
from django.apps import AppConfig
class UserOperationConfig(AppConfig):
name = 'apps.user_operation'
verbose_name="操作管理"
default_app_config="user_operation.apps.UserOperationConfig"
使用python manage.py makemigrations进行数据转移时报错
1.
解决
在这里配置时要注意,最新的版本会在创建app时会将
‘apps.users.apps.UsersConfig’,
这个加进去,就会导致有两个同名的app
将原先的删掉就好了
2.
解决
在settings中缺少这个注册,添加上去就好了
3.
解决
写代码时,将‘.’写成了‘,’ 更改过来就好了
4.
解决
原先用的是username这个字段,但是这个字段在AbstractUser这个抽象类中是存在的,并且不可更改的
将username字段改成name就好了
5.
解决
这里用的应该是mysql,但是在原先的settings字段中配置时,使用的是sqlite3,将sqlite3改成mysql就好了
生成数据库
python manage.py makemigrations
python manage.py migrate
记住在前面的settings的文件中要配置好数据库的用户名和密码
生成成功后通过navicat 查看
然后是导入数据
db_tools下新建文件夹data,然后把前端的json文件(category_data和product_data)拷贝到里面
把brands和goods图片拷贝到media目录下
然后在db_tools下创建import_category_data.py,导入category的数据
#独立使用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 apps.goods.models import GoodsCategory
from db_tools.data.category_data import row_data
#一级类
for lev1_cat in row_data:
#这里处理相当于对json文件的处理
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_goods_data.py导入goods的数据
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 apps.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()
注意这里的os.environ.setdefault(‘DJANGO_SETTINGS_MODULE’, ‘MxShop.settings’)
这里的配置最好是在manage.py中直接复制
运行后数据成功导入
/xadmin管理后台/
1.创建用户 python manage.py createsuperuser
python manage.py runserver 9000
登录
出现的错误
错误1
style_fields = {"goods_desc":"ueditor"}
中间的:号写成了,
错误2
File “D:\Project\pycharm\PycharmProjects\MxShop\extra_apps\xadmin\plugins\inline.py”, line 203, in instance_form
‘one’ if self.max_num == 1 else self.style)(self, instance)
TypeError: ‘NoneType’ object is not callable
更改xadmin\plugins\inline.py的max_num=None 改成max_num=1
max_num = 1
错误3
更改goods下的admin的GoodsAdmin的list_filter中的category_name为category
list_filter=["name","click_num","sold_num","fav_num","goods_num","market_price",
"shop_price","category","is_new","is_hot","add_time"]
错误4
INSTALLED_APPS中要添加
‘crispy_forms’,模块