项目所需要的第三方库
- python版本:python 3.5
- pip安装的第三方库(重要的,需要注意的已经用红色方框标明)
- 其中Django1.8.2最高兼容python3.5,如果安装了python更高版本,则对应的Django版本也需要更高。
- redis版本和celery也存在一定的兼容关系,已知celery最新版本(4.4)对应的redis版本最低为3.2.0,而安装了更低版本的celery,如图中的3.1.25则对redis的版本也有要求,3.1.25的cerely在异步发送邮件时(后续会说明),redis3.0及以上的版本都会报错,所以这里使用了redis2.8.0
Django项目框架搭建
1.文件目录
其中:db文件夹存放模型类的基类,其他的模型类继承该BaseModel类,代码如下:
from django.db import models
class BaseModel(models.Model):
'''模型抽象基类'''
create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
update_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')
is_delete = models.BooleanField(default=False, verbose_name='删除标记')
class Meta:
# 说明是一个抽象模型类
abstract = True
2.manage.py常用指令:
python manage.py startapp appname
python manage.py makemigrations
python manage.py migrate
python manage.py runserver
3.setting.py
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))
# 项目的应用存放在apps目录下,加上这行代码,在之后需要用到应用时,可以不带上前面的apps
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'c#8yfxr40bq+k&xo@iy5@7e+&i6ib30h)np=pfvsrka6_(#$cc'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'tinymce', # 富文本编辑器,需要安装相应的第三方库
'user',
'goods',
'cart',
'order',
)
# 注册项目的应用
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'dailyfresh3.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'dailyfresh3.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'dailyfresh',
'USER': 'root',
'PASSWORD': 'root',
'HOST': 'localhost',
'PORT': 3306,
}
}
# mysql数据库配置
# django认证系统使用的模型类,十分重要的一个配置
AUTH_USER_MODEL='user.User'
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# 选择语言和时区
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
# 富文本编辑器配置,固定
TINYMCE_DEFAULT_CONFIG = {
'theme': 'advance',
'width': 600,
'height': 400,
}
# 发送邮件配置
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# smpt服务地址
EMAIL_HOST = 'smtp.163.com'
EMAIL_PORT = 25
# 发送邮件的邮箱
EMAIL_HOST_USER = 'zhangheng_tust@163.com'
# 在邮箱中设置的客户端授权密码
EMAIL_HOST_PASSWORD = 'EWHOFGKCGSTFIJQT'
# 收件人看到的发件人
EMAIL_FROM = '天天生鲜<zhangheng_tust@163.com>'
# # Django的缓存配置
# CACHES = {
# "default": {
# "BACKEND": "django_redis.cache.RedisCache",
# "LOCATION": "redis://127.0.0.1:6379/9",
# "OPTIONS": {
# "CLIENT_CLASS": "django_redis.client.DefaultClient",
# }
# }
# }
# # 配置session存储
# SESSION_ENGINE = "django.contrib.sessions.backends.cache"
# SESSION_CACHE_ALIAS = "default"
4.项目的urls和应用的urls
项目的urls:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^tinymce/', include('tinymce.urls')), # 富文本编辑器
url(r'^user/', include('user.urls', namespace='user')), # 用户模块
url(r'^cart/', include('cart.urls', namespace='cart')), # 购物车模块
url(r'^order/', include('order.urls', namespace='order')), # 订单模块
url(r'^', include('goods.urls', namespace='goods')), # 商品模块
]
其余应用的urls通过后面的代码展示
5.python与数据库交互,需要在__init__.py中加上两行代码,其中pymysql库需要安装后使用
import pymysql
pymysql.install_as_MySQLdb()
6.模型类代码:
cart/models.py
from django.db import models
# Create your models here.
# 暂无模型
goods/models.py
from django.db import models
from db.base_model import BaseModel
from tinymce.models import HTMLField
# Create your models here.
class GoodsType(BaseModel):
'''商品类型模型类'''
name = models.CharField(max_length=20, verbose_name='种类名称')
logo = models.CharField(max_length=20, verbose_name='标识')
image = models.ImageField(upload_to='type', verbose_name='商品类型图片')
class Meta:
db_table = 'df_goods_type'
verbose_name = '商品种类'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
class GoodsSKU(BaseModel):
'''商品SKU模型类'''
status_choices = (
(0, '下线'),
(1, '上线'),
)
type = models.ForeignKey('GoodsType', verbose_name='商品种类')
goods = models.ForeignKey('Goods', verbose_name='商品SPU')
name = models.CharField(max_length=20, verbose_name='商品名称')
desc = models.CharField(max_length=256, verbose_name='商品简介')
price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='商品价格')
unite = models.CharField(max_length=20, verbose_name='商品单位')
image = models.ImageField(upload_to='goods', verbose_name='商品图片')
stock = models.IntegerField(default=1, verbose_name='商品库存')
sales = models.IntegerField(default=0, verbose_name='商品销量')
status = models.SmallIntegerField(default=1, choices=status_choices, verbose_name='商品状态')
class Meta:
db_table = 'df_goods_sku'
verbose_name = '商品'
verbose_name_plural = verbose_name
class Goods(BaseModel):
'''商品SPU模型类'''
name = models.CharField(max_length=20, verbose_name='商品SPU名称')
# 富文本类型:带有格式的文本
detail = HTMLField(blank=True, verbose_name='商品详情')
class Meta:
db_table = 'df_goods'
verbose_name = '商品SPU'
verbose_name_plural = verbose_name
class GoodsImage(BaseModel):
'''商品图片模型类'''
sku = models.ForeignKey('GoodsSKU', verbose_name='商品')
image = models.ImageField(upload_to='goods', verbose_name='图片路径')
class Meta:
db_table = 'df_goods_image'
verbose_name = '商品图片'
verbose_name_plural = verbose_name
class IndexGoodsBanner(BaseModel):
'''首页轮播商品展示模型类'''
sku = models.ForeignKey('GoodsSKU', verbose_name='商品')
image = models.ImageField(upload_to='banner', verbose_name='图片')
index = models.SmallIntegerField(default=0, verbose_name='展示顺序')
class Meta:
db_table = 'df_index_banner'
verbose_name = '首页轮播商品'
verbose_name_plural = verbose_name
class IndexTypeGoodsBanner(BaseModel):
'''首页分类商品展示模型类'''
DISPLAY_TYPE_CHOICES = (
(0, "标题"),
(1, "图片")
)
type = models.ForeignKey('GoodsType', verbose_name='商品类型')
sku = models.ForeignKey('GoodsSKU', verbose_name='商品SKU')
display_type = models.SmallIntegerField(default=1, choices=DISPLAY_TYPE_CHOICES, verbose_name='展示类型')
index = models.SmallIntegerField(default=0, verbose_name='展示顺序')
class Meta:
db_table = 'df_index_type_goods'
verbose_name = "主页分类展示商品"
verbose_name_plural = verbose_name
class IndexPromotionBanner(BaseModel):
'''首页促销活动模型类'''
name = models.CharField(max_length=20, verbose_name='活动名称')
url = models.URLField(verbose_name='活动链接')
image = models.ImageField(upload_to='banner', verbose_name='活动图片')
index = models.SmallIntegerField(default=0, verbose_name='展示顺序')
class Meta:
db_table = 'df_index_promotion'
verbose_name = "主页促销活动"
verbose_name_plural = verbose_name
order/models.py
from django.db import models
from db.base_model import BaseModel
# Create your models here.
class OrderInfo(BaseModel):
'''订单模型类'''
PAY_METHOD_CHOICES = (
(1, '货到付款'),
(2, '微信支付'),
(3, '支付宝'),
(4, '银联支付')
)
ORDER_STATUS_CHOICES = (
(1, '待支付'),
(2, '待发货'),
(3, '待收货'),
(4, '待评价'),
(5, '已完成')
)
order_id = models.CharField(max_length=128, primary_key=True, verbose_name='订单id')
user = models.ForeignKey('user.User', verbose_name='用户')
addr = models.ForeignKey('user.Address', verbose_name='地址')
pay_method = models.SmallIntegerField(choices=PAY_METHOD_CHOICES, default=3, verbose_name='支付方式')
total_count = models.IntegerField(default=1, verbose_name='商品数量')
total_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='商品总价')
transit_price = models.DecimalField(max_digits=10, decimal_places=2,verbose_name='订单运费')
order_status = models.SmallIntegerField(choices=ORDER_STATUS_CHOICES, default=1, verbose_name='订单状态')
trade_no = models.CharField(max_length=128, verbose_name='支付编号')
class Meta:
db_table = 'df_order_info'
verbose_name = '订单'
verbose_name_plural = verbose_name
class OrderGoods(BaseModel):
'''订单商品模型类'''
order = models.ForeignKey('OrderInfo', verbose_name='订单')
sku = models.ForeignKey('goods.GoodsSKU', verbose_name='商品SKU')
count = models.IntegerField(default=1, verbose_name='商品数目')
price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='商品价格')
comment = models.CharField(max_length=256, verbose_name='评论')
class Meta:
db_table = 'df_order_goods'
verbose_name = '订单商品'
verbose_name_plural = verbose_name
user/models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
from db.base_model import BaseModel
# Create your models here.
class User(AbstractUser, BaseModel):
'''用户模型类'''
class Meta:
db_table = 'df_user'
verbose_name = '用户'
verbose_name_plural = verbose_name
class Address(BaseModel):
'''地址模型类'''
user = models.ForeignKey('User', verbose_name='所属账户')
receiver = models.CharField(max_length=20, verbose_name='收件人')
addr = models.CharField(max_length=256, verbose_name='收件地址')
zip_code = models.CharField(max_length=6, null=True, verbose_name='邮政编码')
phone = models.CharField(max_length=11, verbose_name='联系电话')
is_default = models.BooleanField(default=False, verbose_name='是否默认')
class Meta:
db_table = 'df_address'
verbose_name = '地址'
verbose_name_plural = verbose_name
7.执行迁移命令,在数据库生成对应的数据表,最后启动服务器,验证是否正确运行。