本文是幕课网和黑马的生鲜电商结合整理,版本不是原教程,全用的是当前最新版本,为了方便后来学习的参考,
如果部份内容对大家有用,可以转到达自己的博客
在新建之前 先建一个虚拟环境,mkvirtualenv VueShop
并安装必要的组件:
djangorestframework
django
django-filter
Markdown
Pillow
pymysql
配置环境
在主init 上配置引挚:就是主目录的 —init__.py 文件中
import pymysql
pymysql.install_as_MySQLdb()
配置数据库:电商项目用到第三方登录,所以数据引挚要配置一下,红色部份
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': "mxshop",
'USER':'root',
'PASSWORD':'142857',
'HOST':"127.0.0.1",
'PORT': '3306',
"OPTIONS":{"init_command":"SET default_storage_engine=INNODB;"}
}
}
根目录新建以下文件,用于管理项目
新建所有的apps在下面新建所需的路由 这儿不是新建文件。而是新建app 然后拖入 app分别是
goods ,trade user_operation users
新建extra_apps ,用于第三方插件
新建templates ,,用于模板
新建media ,用于图片
新建 存放静态文件
新建 db_tools 用于脚本存放
mark目录 ->
Mark - Durectirt as Sources Root
简化导入目录:
为了方便导入,需要把上些目录配置成根目录搜索路径:在配置文件中头部 import os 下面加入:
import sys
BASE_DIR = os.path.dirname(os,path.dirname(os.path.abspath(__file__)))
sys.path.insert(0,BASE_DIR')
sys.path.insert(0,os.path.join(BASE_DIR,'apps'))
sys.path.insert(0,os.path.join(BASE_DIR,'extra_apps'))
图片参考
user apps表模型数据表建立:
第一个用户表,,这儿继承用户表:
from django.contrib.auth.models import AbstractUser
在编写需要改的字段:
class UserProfile(AbstractUser): """ 用户 """ name = models.CharField(max_length=30, null=True, blank=True, verbose_name="姓名") birthday = models.DateField(null=True, blank=True, verbose_name="出生年月") gender = models.CharField(max_length=6, choices=(("male", u"男"), ("female", "女")), default="female", verbose_name="性别") mobile = models.CharField(null=True, blank=True, max_length=11, verbose_name="电话") email = models.EmailField(max_length=100, null=True, blank=True, verbose_name="邮箱") class Meta: verbose_name = "用户" verbose_name_plural = verbose_name def __str__(self): return self.username class VerifyCode(models.Model): """ 短信验证码 """ code = models.CharField(max_length=10, verbose_name="验证码") mobile = models.CharField(max_length=11, verbose_name="电话") add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间") class Meta: verbose_name = "短信验证码" verbose_name_plural = verbose_name def __str__(self): return self.code
写好表后,因为用户是继随的,所以需要在高置文儿加入配置 ,以便识别:红色部份:
....................................
DEBUG = True
ALLOWED_HOSTS = ['*']
AUTH_USER_MODEL = 'users.UserProfile'
# Application definition
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
......................................................................................................................................................................
商品类 goods
from datetime import datetime from django.db import models from DjangoUeditor.models import UEditorField # Create your models here. class GoodsCategory(models.Model): """ 商品类别 """ CATEGORY_TYPE = ( (1, "一级类目"), (2, "二级类目"), (3, "三级类目"), ) name = models.CharField(default="", max_length=30, verbose_name="类别名", help_text="类别名") code = models.CharField(default="", max_length=30, verbose_name="类别code", help_text="类别code") desc = models.TextField(default="", verbose_name="类别描述", help_text="类别描述") category_type = models.IntegerField(choices=CATEGORY_TYPE, verbose_name="类目级别", help_text="类目级别") parent_category = models.ForeignKey("self", null=True, blank=True, verbose_name="父类目级别", help_text="父目录", related_name="sub_cat",on_delete=models.CASCADE) is_tab = models.BooleanField(default=False, verbose_name="是否导航", help_text="是否导航") add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间") class Meta: verbose_name = "商品类别" verbose_name_plural = verbose_name def __str__(self): return self.name class GoodsCategoryBrand(models.Model): """ 品牌名 """ category = models.ForeignKey(GoodsCategory, related_name='brands', null=True, blank=True, verbose_name="商品类目",on_delete=models.CASCADE) name = models.CharField(default="", max_length=30, verbose_name="品牌名", help_text="品牌名") desc = models.TextField(default="", max_length=200, verbose_name="品牌描述", help_text="品牌描述") image = models.ImageField(max_length=200, upload_to="brands/") add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间") class Meta: verbose_name = "品牌" verbose_name_plural = verbose_name db_table = "goods_goodsbrand" def __str__(self): return self.name class Goods(models.Model): """ 商品 """ category = models.ForeignKey(GoodsCategory, verbose_name="商品类目",on_delete=models.CASCADE) goods_sn = models.CharField(max_length=50, default="", verbose_name="商品唯一货号") name = models.CharField(max_length=100, verbose_name="商品名") click_num = models.IntegerField(default=0, verbose_name="点击数") sold_num = models.IntegerField(default=0, verbose_name="商品销售量") fav_num = models.IntegerField(default=0, verbose_name="收藏数") goods_num = models.IntegerField(default=0, verbose_name="库存数") market_price = models.FloatField(default=0, verbose_name="市场价格") shop_price = models.FloatField(default=0, verbose_name="本店价格") goods_brief = models.TextField(max_length=500, verbose_name="商品简短描述") goods_desc = UEditorField(verbose_name=u"内容", imagePath="goods/images/", width=1000, height=300, filePath="goods/files/", default='') ship_free = models.BooleanField(default=True, verbose_name="是否承担运费") goods_front_image = models.ImageField(upload_to="goods/images/", null=True, blank=True, verbose_name="封面图") is_new = models.BooleanField(default=False, verbose_name="是否新品") is_hot = models.BooleanField(default=False, verbose_name="是否热销") add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间") class Meta: verbose_name = '商品' verbose_name_plural = verbose_name def __str__(self): return self.name class IndexAd(models.Model): category = models.ForeignKey(GoodsCategory, related_name='category',verbose_name="商品类目",on_delete=models.CASCADE) goods =models.ForeignKey(Goods, related_name='goods',on_delete=models.CASCADE) class Meta: verbose_name = '首页商品类别广告' verbose_name_plural = verbose_name def __str__(self): return self.goods.name class GoodsImage(models.Model): """ 商品轮播图 """ goods = models.ForeignKey(Goods, verbose_name="商品", related_name="images",on_delete=models.CASCADE) image = models.ImageField(upload_to="", verbose_name="图片", null=True, blank=True) add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间") class Meta: verbose_name = '商品图片' verbose_name_plural = verbose_name def __str__(self): return self.goods.name class Banner(models.Model): """ 轮播的商品 """ goods = models.ForeignKey(Goods, verbose_name="商品",on_delete=models.CASCADE) image = models.ImageField(upload_to='banner', verbose_name="轮播图片") index = models.IntegerField(default=0, verbose_name="轮播顺序") add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间") class Meta: verbose_name = '轮播商品' verbose_name_plural = verbose_name def __str__(self): return self.goods.name class HotSearchWords(models.Model): """ 热搜词 """ keywords = models.CharField(default="", max_length=20, verbose_name="热搜词") index = models.IntegerField(default=0, verbose_name="排序") add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间") class Meta: verbose_name = '热搜词' verbose_name_plural = verbose_name def __str__(self): return self.keywords
用户操作表 表名:user_operation
from datetime import datetime from django.db import models from django.contrib.auth import get_user_model from goods.models import Goods # Create your models here. User = get_user_model() class UserFav(models.Model): """ 用户收藏 """ user = models.ForeignKey(User, verbose_name="用户",on_delete=models.CASCADE) goods = models.ForeignKey(Goods, verbose_name="商品", help_text="商品id",on_delete=models.CASCADE) add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间") class Meta: verbose_name = '用户收藏' verbose_name_plural = verbose_name unique_together = ("user", "goods") def __str__(self): return self.user.username class UserLeavingMessage(models.Model): """ 用户留言 """ MESSAGE_CHOICES = ( (1, "留言"), (2, "投诉"), (3, "询问"), (4, "售后"), (5, "求购") ) user = models.ForeignKey(User, verbose_name="用户",on_delete=models.CASCADE) message_type = models.IntegerField(default=1, choices=MESSAGE_CHOICES, verbose_name="留言类型", help_text=u"留言类型: 1(留言),2(投诉),3(询问),4(售后),5(求购)") subject = models.CharField(max_length=100, default="", verbose_name="主题") message = models.TextField(default="", verbose_name="留言内容", help_text="留言内容") file = models.FileField(upload_to="message/images/", verbose_name="上传的文件", help_text="上传的文件") add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间") class Meta: verbose_name = "用户留言" verbose_name_plural = verbose_name def __str__(self): return self.subject class UserAddress(models.Model): """ 用户收货地址 """ user = models.ForeignKey(User, verbose_name="用户",on_delete=models.CASCADE) province = models.CharField(max_length=100, default="", verbose_name="省份") city = models.CharField(max_length=100, default="", verbose_name="城市") district = models.CharField(max_length=100, default="", verbose_name="区域") address = models.CharField(max_length=100, default="", verbose_name="详细地址") signer_name = models.CharField(max_length=100, default="", verbose_name="签收人") signer_mobile = models.CharField(max_length=11, default="", verbose_name="电话") add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间") class Meta: verbose_name = "收货地址" verbose_name_plural = verbose_name def __str__(self): return self.address
支 付订类表:trade
from datetime import datetime from django.db import models from django.contrib.auth import get_user_model from goods.models import Goods # Create your models here. User = get_user_model() class UserFav(models.Model): """ 用户收藏 """ user = models.ForeignKey(User, verbose_name="用户",on_delete=models.CASCADE) goods = models.ForeignKey(Goods, verbose_name="商品", help_text="商品id",on_delete=models.CASCADE) add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间") class Meta: verbose_name = '用户收藏' verbose_name_plural = verbose_name unique_together = ("user", "goods") def __str__(self): return self.user.username class UserLeavingMessage(models.Model): """ 用户留言 """ MESSAGE_CHOICES = ( (1, "留言"), (2, "投诉"), (3, "询问"), (4, "售后"), (5, "求购") ) user = models.ForeignKey(User, verbose_name="用户",on_delete=models.CASCADE) message_type = models.IntegerField(default=1, choices=MESSAGE_CHOICES, verbose_name="留言类型", help_text=u"留言类型: 1(留言),2(投诉),3(询问),4(售后),5(求购)") subject = models.CharField(max_length=100, default="", verbose_name="主题") message = models.TextField(default="", verbose_name="留言内容", help_text="留言内容") file = models.FileField(upload_to="message/images/", verbose_name="上传的文件", help_text="上传的文件") add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间") class Meta: verbose_name = "用户留言" verbose_name_plural = verbose_name def __str__(self): return self.subject class UserAddress(models.Model): """ 用户收货地址 """ user = models.ForeignKey(User, verbose_name="用户",on_delete=models.CASCADE) province = models.CharField(max_length=100, default="", verbose_name="省份") city = models.CharField(max_length=100, default="", verbose_name="城市") district = models.CharField(max_length=100, default="", verbose_name="区域") address = models.CharField(max_length=100, default="", verbose_name="详细地址") signer_name = models.CharField(max_length=100, default="", verbose_name="签收人") signer_mobile = models.CharField(max_length=11, default="", verbose_name="电话") add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间") class Meta: verbose_name = "收货地址" verbose_name_plural = verbose_name def __str__(self): return self.address
支付订单是动态获取的用户类,注意这个用法
from django.contrib.auth import get_user_model
User = get_user_model()
导放表后,开始使用后台使用的xadmin ,,用于生成后台数据。在usres app中新建一个adminx.py 添加内容:
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 = "mxshop" # 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)
在user_operation 下新建adminx.py
#!/usr/bin/env python # encoding: utf-8 """ @version: 1.0 @author: liyao @license: Apache Licence @contact: yli@posbao.net @site: http://www.piowind.com/ @software: PyCharm @file: adminx.py @time: 2017/7/4 17:04 """ 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)
在goods 下新建adminx.py
#!/usr/bin/env python # encoding: utf-8 """ @version: 1.0 @author: liyao @license: Apache Licence @contact: yli@posbao.net @site: http://www.piowind.com/ @software: PyCharm @file: adminx.py @time: 2017/7/4 17:04 """ 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)
在rtade 下新建adminx.py
# -*- coding: utf-8 -*- __author__ = 'bobby' 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)
数据库建好了,后台配好了,新建一个extra_apps的主文件,用于存放第三方文件,把下载好的xadmin 放入主文件目录 ,这儿还有一个富文本组件也放这个目录
新建一个 static 用于存放静态文件。找配置文件中找到 STATIC_URL = '/static/' 加入:
STATIC_URL = '/static/'
STATICFILES_DIRS=(
os.path.join(BASE_DIR,'static'),
)
新建一个media 用于存放图片文件,可能用不上先建一个在说
在配置尾部加入:
MEDIA_URL='/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
配置数据库:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mxshop',
'USER': 'root',
'PASSWORD': '142857',
'HOST': '127.0.0.1',
'PORT': '3306',
"OPTIONS": {"init_command": "SET default_storage_engine=INNODB;"},
}
}
配置usre的目录使用文件:因为我们继承了默认的用户文件。在其它app 不知道,
AUTH_USER_MODEL = "users.UserProfile"
增加apps 启动文件:
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"crispy_forms",
"rest_framework",
"DjangoUeditor",
"users",
"goods",
"trade",
"xadmin",
"user_operation",
]
迁移数据库
makemigrations
migrate
到此为此,整个天天生鲜平台初步做好,关于逻辑部份,在另一篇继续