项目2
接下来,我们把注册过程中一些注册信息(例如:短信验证码)和session缓存到redis数据库中。
安装django-redis。
pip install django-redis
在settings/dev.py配置中添加一下代码:
# 设置redis缓存 CACHES = { # 默认缓存 "default": { "BACKEND": "django_redis.cache.RedisCache", # 项目上线时,需要调整这里的路径 "LOCATION": "redis://127.0.0.1:6379/0", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } }, # 提供给xadmin或者admin的session存储 "session": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } }, # 提供存储短信验证码 "sms_code":{ "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/2", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } # 设置xadmin用户登录时,登录信息session保存到redis SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "session"
关于django-redis 的使用,说明文档可见http://django-redis-chs.readthedocs.io/zh_CN/latest/
django-redis提供了get_redis_connection的方法,通过调用get_redis_connection方法传递redis的配置名称可获取到redis的连接对象,通过redis连接对象可以执行redis命令
https://redis-py.readthedocs.io/en/latest/
使用范例:
from django_redis import get_redis_connection // 链接redis数据库 redis_conn = get_redis_connection("sms_code") // 操作redis redis_conn.setex("键","时间(秒)","值") # 这个redis类把终端命令封装成了redis类的方法,命令的选项编程了方法的参数,所以这段代码的操作,等同于在终端下 sexex 键 时间 值
在登录后的平台上面获取一下信息:
ACCOUNT SID:8a216da86e011fa3016e4aedea792a4e AUTH TOKEN : 4fee1ea5d1024bce948db54b9161c97e AppID(默认):8a216da86e011fa3016e4aedeacb2a54 Rest URL(生产): app.cloopen.com:8883 [项目上线时使用真实短信发送服务器] Rest URL(开发): sandboxapp.cloopen.com:8883 [项目开发时使用沙箱短信发送服务器]
找到sdkdemo进行下载
在开发过程中,为了节约发送短信的成本,可以把自己的或者同事的手机加入到测试号码中.
把云通讯的sdk保存到libs目录下, 并修改里面的基本配置信息。
sms.py,代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# -*- coding:utf-8 -*- from .CCPRestSDK import REST from django.conf import settings # 说明:主账号,登陆云通讯网站后,可在"控制台-应用"中看到开发者主账号ACCOUNT SID _accountSid = settings.SMS["_accountSid"] # 说明:主账号Token,登陆云通讯网站后,可在控制台-应用中看到开发者主账号AUTH TOKEN _accountToken = settings.SMS["_accountToken"] # 6dd01b2b60104b3dbc88b2b74158bac6 # 请使用管理控制台首页的APPID或自己创建应用的APPID _appId = settings.SMS["_appId"] # 8a216da863f8e6c20164139688400c21 # 说明:请求地址,生产环境配置成app.cloopen.com _serverIP = settings.SMS["_serverIP"] # 说明:请求端口 ,生产环境为8883 _serverPort = settings.SMS["_serverPort"] # 说明:REST API版本号保持不变 _softVersion = '2013-12-26' # 云通讯官方提供的发送短信代码实例 # # 发送模板短信 # # @param to 手机号码 # # @param datas 内容数据 格式为数组 例如:{'12','34'},如不需替换请填 '' # # @param $tempId 模板Id # # def sendTemplateSMS(to, datas, tempId): # # 初始化REST SDK # rest = REST(serverIP, serverPort, softVersion) # rest.setAccount(accountSid, accountToken) # rest.setAppId(appId) # # result = rest.sendTemplateSMS(to, datas, tempId) # for k, v in result.iteritems(): # # if k == 'templateSMS': # for k, s in v.iteritems(): # print '%s:%s' % (k, s) # else: # print '%s:%s' % (k, v) class CCP(object): """发送短信的辅助类""" def __new__(cls, *args, **kwargs): # 判断是否存在类属性_instance,_instance是类CCP的唯一对象,即单例 if not hasattr(CCP, "_instance"): cls._instance = super(CCP, cls).__new__(cls, *args, **kwargs) cls._instance.rest = REST(_serverIP, _serverPort, _softVersion) cls._instance.rest.setAccount(_accountSid, _accountToken) cls._instance.rest.setAppId(_appId) return cls._instance def send_template_sms(self, to, datas, temp_id): """发送模板短信""" # @param to 手机号码 # @param datas 内容数据 格式为数组 例如:{'12','34'},如不需替换请填 '' # @param temp_id 模板Id result = self.rest.sendTemplateSMS(to, datas, temp_id) # 如果云通讯发送短信成功,返回的字典数据result中statuCode字段的值为"000000" return result.get("statusCode") == "000000" if __name__ == '__main__': ccp = CCP() # 注意: 测试的短信模板编号为1[以后申请了企业账号以后可以有更多的模板] # 参数1: 客户端手机号码,测试时只能发给测试号码 # 参数2: 短信模块中的数据 # 短信验证码 # 短信验证码有效期提示 # 参数3: 短信模板的id,开发测试时,只能使用1 ccp.send_template_sms('17610211902', ['1234',"5分钟"], 1)
配置文件,代码:
# 云通讯短信 SMS = { # 说明:主账号,登陆云通讯网站后,可在"控制台-应用"中看到开发者主账号ACCOUNT SID "_accountSid":'8a216da863f8e6c20164139687e80c1b', # 说明:主账号Token,登陆云通讯网站后,可在控制台-应用中看到开发者主账号AUTH TOKEN "_accountToken":'4fee1ea5d1024bce948db54b9161c97e', # 请使用管理控制台首页的APPID或自己创建应用的APPID "_appId":'8a216da86e011fa3016e4aedeacb2a54', # 说明:请求地址,生产环境配置成app.cloopen.com "_serverIP":'sandboxapp.cloopen.com', # 说明:请求端口 ,生产环境为8883 "_serverPort": "8883", }
视图代码:
from .models import User from rest_framework import status class MobileAPIView(APIView): """手机号验证接口""" def get(self,request,mobile): """验证手机号是否已经被注册了 url: /users/mobile/(?P<mobile>1[3-9]\d{9})/ """ try: # 查询出来结果有用户,在表示已经被注册了 User.objects.get(mobile=mobile) return Response({"status":False,"message":"当前手机号已经被注册了"},status=status.HTTP_400_BAD_REQUEST) except User.DoesNotExist: return Response({"status":True})
路由代码:
re_path("mobile/(?P<mobile>1[3-9]\d{9})/", views.MobileAPIView.as_view() ),
视图代码:
from rest_framework.views import APIView from rest_framework.response import Response from luffyapi.libs.geetest import GeetestLib from django.conf import settings #.... from luffyapi.libs.yuntongxun.sms import CCP import random from luffyapi.settings import constants class SMSAPIView(APIView): """短信接口API""" def get(self,request,mobile): """发送短信""" # 验证码手机号的有效性 try: User.objects.get(mobile=mobile) return Response({"status": False, "message": "当前手机号已经被注册了"},status=status.HTTP_400_BAD_REQUEST) except User.DoesNotExist: pass from django_redis import get_redis_connection redis_conn = get_redis_connection("sms_code") # 验证短信的发送时间是否超过了1分钟,1分钟内只能发送一次 if redis_conn.get("sms_interval_%s" % mobile): return Response({"status": False, "message": "请勿频繁发送短信!"},status=status.HTTP_400_BAD_REQUEST) # 使用随机数生成验证码,不足6位数字的,使用字符串格式化,在数字左边补充"0" sms_code = "%06d" % random.randint(1000, 999999) # 把验证码保存到redis pipe = redis_conn.pipeline() # 创建管道对象 pipe.multi() # 开启事务 pipe.setex("sms_%s" % mobile, constants.SMS_EXPIRE_TIME, sms_code ) pipe.setex("sms_interval_%s" % mobile, constants.SMS_INTERVAL_TIME, "_") pipe.execute() # 执行管道中所有的命令 ccp = CCP() result = ccp.send_template_sms(mobile, [sms_code, constants.SMS_EXPIRE_TIME//60 ], constants.SMS_TEMPLATE_ID) return Response({"status": result})
路由代码:
re_path("sms/(?P<mobile>1[3-9]\d{9})/", views.SMSAPIView.as_view() ),
配置文件settings/dev.py,代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 云通讯短信 SMS = { # 说明:主账号,登陆云通讯网站后,可在"控制台-应用"中看到开发者主账号ACCOUNT SID "_accountSid":'8a216da86e011fa3016e4aedea792a4e', # 说明:主账号Token,登陆云通讯网站后,可在控制台-应用中看到开发者主账号AUTH TOKEN "_accountToken":'4fee1ea5d1024bce948db54b9161c97e', # 请使用管理控制台首页的APPID或自己创建应用的APPID "_appId":'8a216da86e011fa3016e4aedeacb2a54', # 说明:请求地址,生产环境配置成app.cloopen.com "_serverIP":'sandboxapp.cloopen.com', # 说明:请求端口 ,生产环境为8883 "_serverPort": "8883", }
配置常量settings/constants.py,代码:
# 验证码有效使用时间[单位: 秒] SMS_EXPIRE_TIME = 5 * 60 # 短信发送的间隔时间 SMS_INTERVAL_TIME = 60 # 短信模板ID SMS_TEMPLATE_ID = 1
视图代码:
from rest_framework.generics import CreateAPIView from .serializers import UserModelSerializer class UserAPIView(CreateAPIView): queryset = User.objects.all() serializer_class = UserModelSerializer
序列化器,代码:
在users下创建一个serializers.py
from rest_framework import serializers from .models import User import re from django_redis import get_redis_connection import logging log = logging.getLogger("django") class UserModelSerializer(serializers.ModelSerializer): sms_code = serializers.CharField(max_length=6, min_length=4, write_only=True, help_text="短信验证码") token = serializers.CharField(max_length=1000, read_only=True, help_text="token令牌") class Meta: model = User fields = ["mobile", "password", "sms_code", "token", "id", "username"] extra_kwargs = { "mobile": {"write_only": True, }, "password": {"write_only": True, }, "id": {"read_only": True, }, "username": {"read_only": True, } } def validate(self, attrs): """验证数据""" # 验证手机号是否格式正确 mobile = attrs.get("mobile") if not re.match("^1[3-9]\d{9}$", mobile): return serializers.ValidationError("对不起,手机号码格式不正确!") # 验证手机号是否被注册了 try: User.objects.get(mobile=mobile) return serializers.ValidationError("对不起,手机号码已经被注册了!") except User.DoesNotExist: pass # 作业: 验证密码的长度,必须时6-16位字符 # 验证手机短信验证码是否过期了或者错误 sms_code = attrs.get("sms_code") redis_conn = get_redis_connection("sms_code") code_bytes = redis_conn.get("sms_%s" % mobile) if not code_bytes or code_bytes.decode() != sms_code: """如果redis不存在对应手机的短信验证码或者提取出来的短信验证码双方不一致都是验证失败""" return serializers.ValidationError("对不起,验证码过期或错误!") # 删除短信验证码的记录 redis_conn.delete("sms_%s" % mobile) return attrs def create(self, validated_data): """添加用户数据""" # 移除客户端提交过来的短信验证码的信息 del validated_data["sms_code"] # 对数据进行保存和完成密码加密 try: validated_data["username"] = validated_data["mobile"] # 添加用户信息 user = super().create(validated_data=validated_data) # 更新密码 user.set_password(validated_data.get("password")) user.save() except: log.error("用户注册信息保存失败!") return serializers.ValidationError("对不起,用户注册保存信息失败!请联系客服工作人员") # 在添加用户成功以后,需要保存登录状态返回给客户端[实现注册免登录] # 使用restframework_jwt提供的代码 生成token from rest_framework_jwt.settings import api_settings jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) user.token = jwt_encode_handler(payload) # 把token返回给客户端 return user
users/urls.py,路由代码:
path("", views.UserAPIView.as_view() ),
调整前端的页面,添加一个发送短信功能,
Register/html代码:
替换原先验证码代码
<div class="sms-box"> <input v-model = "sms" type="text" placeholder="输入验证码" class="user"> <div class="sms-btn" @click="smsHandle">点击发送短信</div> </div>
css,代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
.sms-box{ position: relative; } .sms-btn{ font-size: 14px; color: #ffc210; letter-spacing: .26px; position: absolute; right: 16px; top: 10px; cursor: pointer; overflow: hidden; background: #fff; border-left: 1px solid #484848; padding-left: 16px; padding-bottom: 4px; }
script,代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
export default { name: 'Register', data(){ return { sms:"", mobile:"", password:"", interval_text: "点击发送短信", is_send_interval:false, // 是否在60秒内发送短信的状态,false表示没有 } }, created(){ }, methods:{ check_mobile(){ // 验证格式 if( ! /^1[3-9]\d{9}$/.test(this.mobile) ){ this.$message.error("对不起,手机号格式不正确!"); return ; } // 验证是否被注册了 this.$axios.get(`${this.$settings.Host}/user/mobile/${this.mobile}/`).then(response=>{ }).catch(error=>{ if(error.response.status === 400){ this.$message.error("对不起,当前手机已被注册!"); }else{ this.$message.error("网络异常,请联系网站客服工作人员!"); } }); }, smsHandle(){ // 判断是否在60内曾经有发送短信的记录 if(this.is_send_interval){ this.$message.error("请不要频繁点击发送短信!"); return ; } // 短信发送处理 this.$axios.get(`${this.$settings.Host}/user/sms/${this.mobile}/`).then(response=>{ if(response.data.status){ this.$message.success("短信已发送,请注意留意您的手机!"); // 更新发送短信的间隔状态 this.is_send_interval = true; let time = 60; let t = setInterval(()=>{ if(time<1){ this.interval_text = "点击发送短信"; this.is_send_interval = false; // 允许用户重新点击发送短信 clearInterval(t); // 关闭定时器 }else{ time--; this.interval_text = `${time}后点击重新发送` } },1000); } }).catch(error=>{ this.$message.error("对不起,发送短信失败!"); }) }, registerHandle(){ // 注册处理 this.$axios.post(`${this.$settings.Host}/user/`, { mobile:this.mobile, sms_code: this.sms, password: this.password, }).then(response=>{ if(response.status===201){ // 注册成功 sessionStorage.user_token = response.data.token; sessionStorage.user_id = response.data.id; sessionStorage.user_name = response.data.username; let self = this; this.$alert("注册成功!","路飞学城",{ callback(){ self.$router.push("/"); } }) }else{ // 注册失败 this.$message.error("对不起,注册用户失败!请重新注册或联系网站客服工作人员!"); } }).catch(error=>{ this.$message.error("对不起,注册用户失败!请重新注册或联系网站客服工作人员!"); }) } }, };
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<template> <div class="sms-box"> <input v-model = "sms" type="text" placeholder="输入验证码" class="user"> <div class="sms-btn" @click="smsHandle">{{interval_text}}</div> </div> </template> <script> export default { name: 'Register', data(){ return { sms:"", mobile:"", password:"", interval_text: "点击发送短信", is_send_interval:false, // 是否在60秒内发送短信的状态,false表示没有 } }, created(){ }, methods:{ check_mobile(){ // 验证格式 if( ! /^1[3-9]\d{9}$/.test(this.mobile) ){ this.$message.error("对不起,手机号格式不正确!"); return ; } // 验证是否被注册了 this.$axios.get(`${this.$settings.Host}/user/mobile/${this.mobile}/`).then(response=>{ }).catch(error=>{ if(error.response.status === 400){ this.$message.error("对不起,当前手机已被注册!"); }else{ this.$message.error("网络异常,请联系网站客服工作人员!"); } }); }, smsHandle(){ // 判断是否在60内曾经有发送短信的记录 if(this.is_send_interval){ this.$message.error("请不要频繁点击发送短信!"); return ; } // 短信发送处理 this.$axios.get(`${this.$settings.Host}/user/sms/${this.mobile}/`).then(response=>{ if(response.data.status){ this.$message.success("短信已发送,请注意留意您的手机!"); // 更新发送短信的间隔状态 this.is_send_interval = true; let time = 60; let t = setInterval(()=>{ if(time<1){ this.interval_text = "点击发送短信"; this.is_send_interval = false; // 允许用户重新点击发送短信 clearInterval(t); // 关闭定时器 }else{ time--; this.interval_text = `${time}后点击重新发送` } },1000); } }).catch(error=>{ this.$message.error("对不起,发送短信失败!"); }) }, registerHandle(){ // 注册处理 this.$axios.post(`${this.$settings.Host}/user/`, { mobile:this.mobile, sms_code: this.sms, password: this.password, }).then(response=>{ if(response.status===201){ // 注册成功 sessionStorage.user_token = response.data.token; sessionStorage.user_id = response.data.id; sessionStorage.user_name = response.data.username; let self = this; this.$alert("注册成功!","路飞学城",{ callback(){ self.$router.push("/"); } }) }else{ // 注册失败 this.$message.error("对不起,注册用户失败!请重新注册或联系网站客服工作人员!"); } }).catch(error=>{ this.$message.error("对不起,注册用户失败!请重新注册或联系网站客服工作人员!"); }) } }, }; </script>
celery
在main.py主程序中对django的配置文件进行加载
安装
pip install -U celery
创建
luffyapi/ ├── my_celery/ ├── config.py # 配置文件 ├── __init__.py ├── main.py # 主程序 └── sms/ # 一个目录可以放置多个任务,该目录下存放当前任务执行时需要的模块或依赖 └── tasks.py # 任务的文件,名称必须是这个!!!
main.py,代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 主程序 from celery import Celery # 创建celery实例对象 app = Celery("luffy") # 把celery和django进行组合,识别和加载django的配置文件,这句话从wsgi,复制过来 import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'luffyapi.settings.dev') # 对django框架执行初始化 import django django.setup() # 通过app对象加载配置 app.config_from_object("my_celery.config") # 自动搜索并加载任务 # 参数必须必须是一个列表,里面的每一个任务都是任务的路径名称 # app.autodiscover_tasks(["任务1","任务2",....]) app.autodiscover_tasks(["my_celery.sms","my_celery.cache"])
config.py
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 任务队列的链接地址 broker_url = 'redis://127.0.0.1:6379/15' # 结果队列的链接地址 result_backend = 'redis://127.0.0.1:6379/14'
sms/tasks.py
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from my_celery.main import app from .yuntongxun.sms import CCP from luffyapi.settings import constants import logging log = logging.getLogger("django") @app.task(name="send_sms") def send_sms(mobile,sms_code): """异步发送短信""" ccp = CCP() try: result = ccp.send_template_sms(mobile, [sms_code, constants.SMS_EXPIRE_TIME//60 ], constants.SMS_TEMPLATE_ID) return result except: log.error("发送短信验证码失败!手机号:%s"% mobile)
启动
# 启动Celery的命令 # 强烈建议切换目录到项目的根目录下启动celery!! # celery -A my_celery.main worker --loglevel=info
在users/views下
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from rest_framework.views import APIView # Create your views here. class CaptchaAPIView(APIView): """验证码接口""" def get(self,request): """提供生成验证码流水号""" user_id = 'test' gt = GeetestLib(settings.GEETEST["pc_geetest_id"], settings.GEETEST["pc_geetest_key"]) status = gt.pre_process(user_id) # request.session[gt.GT_STATUS_SESSION_KEY] = status # request.session["user_id"] = user_id response_str = gt.get_response_str() return Response(response_str) def post(self,request): """二次验证""" gt = GeetestLib(settings.GEETEST["pc_geetest_id"], settings.GEETEST["pc_geetest_key"]) challenge = request.data.get(gt.FN_CHALLENGE, '') validate = request.data.get(gt.FN_VALIDATE, '') seccode = request.data.get(gt.FN_SECCODE, '') # status = request.session[gt.GT_STATUS_SESSION_KEY] # user_id = request.session["user_id"] # if status: # result = gt.success_validate(challenge, validate, seccode, user_id) # else: result = gt.failback_validate(challenge, validate, seccode) result = {"status": "success"} if result else {"status": "fail"} # if result: # result = {"status": "success"} # else: # result = {"status": "fail"} return Response(result) from .models import User from rest_framework import status class MobileAPIView(APIView): """手机号验证接口""" def get(self,request,mobile): """验证手机号是否已经被注册了 url: /users/mobile/(?P<mobile>1[3-9]\d{9})/ """ try: # 查询出来结果有用户,在表示已经被注册了 User.objects.get(mobile=mobile) return Response({"status":False,"message":"当前手机号已经被注册了"},status=status.HTTP_400_BAD_REQUEST) except User.DoesNotExist: return Response({"status":True}) from rest_framework.views import APIView from rest_framework.response import Response from luffyapi.libs.geetest import GeetestLib from django.conf import settings #.... import random from luffyapi.settings import constants class SMSAPIView(APIView): """短信接口API""" def get(self,request,mobile): """发送短信""" # 验证码手机号的有效性 try: User.objects.get(mobile=mobile) return Response({"status": False, "message": "当前手机号已经被注册了"},status=status.HTTP_400_BAD_REQUEST) except User.DoesNotExist: pass from django_redis import get_redis_connection redis_conn = get_redis_connection("sms_code") # 验证短信的发送时间是否超过了1分钟,1分钟内只能发送一次 if redis_conn.get("sms_interval_%s" % mobile): return Response({"status": False, "message": "请勿频繁发送短信!"},status=status.HTTP_400_BAD_REQUEST) # 使用随机数生成验证码,不足6位数字的,使用字符串格式化,在数字左边补充"0" sms_code = "%06d" % random.randint(1000, 999999) # 把验证码保存到redis pipe = redis_conn.pipeline() # 创建管道对象 pipe.multi() # 开启事务 pipe.setex("sms_%s" % mobile, constants.SMS_EXPIRE_TIME, sms_code ) pipe.setex("sms_interval_%s" % mobile, constants.SMS_INTERVAL_TIME, "_") pipe.execute() # 执行管道中所有的命令 # ccp = CCP() # result = ccp.send_template_sms(mobile, [sms_code, constants.SMS_EXPIRE_TIME//60 ], constants.SMS_TEMPLATE_ID) # 调用celery执行异步任务 from my_celery.sms.tasks import send_sms send_sms.delay(mobile,sms_code) return Response({"status": True}) from rest_framework.generics import CreateAPIView from .serializers import UserModelSerializer class UserAPIView(CreateAPIView): queryset = User.objects.all() serializer_class = UserModelSerializer
变动代码
from my_celery.sms.tasks import send_sms send_sms.delay(mobile,sms_code) return Response({"status": True})
然后把课程列表页面组件Course.vue放到前端项目中.
Course.vue
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<template> <div class="course"> <Header></Header> <div class="main"> <!-- 筛选条件 --> <div class="condition"> <ul class="cate-list"> <li class="title">课程分类:</li> <li class="this">全部</li> <li>Python</li> <li>Linux运维</li> <li>Python进阶</li> <li>开发工具</li> <li>Go语言</li> <li>机器学习</li> <li>技术生涯</li> </ul> <div class="ordering"> <ul> <li class="title">筛 选: </li> <li class="default this">默认</li> <li class="hot this">人气</li> <li class="price this">价格</li> </ul> <p class="condition-result">共21个课程</p> </div> </div> <!-- 课程列表 --> <div class="course-list"> <div class="course-item"> <div class="course-image"> <img src="/static/image/course-cover.jpeg" alt=""> </div> <div class="course-info"> <h3><router-link to="/course/detail/1">Python开发21天入门</router-link> <span><img src="/static/image/avatar1.svg" alt="">100人已加入学习</span></h3> <p class="teather-info">Alex 金角大王 老男孩Python教学总监 <span>共154课时/更新完成</span></p> <ul class="lesson-list"> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码初识编码初识编码</span> <span class="free">免费</span></li> </ul> <div class="pay-box"> <span class="discount-type">限时免费</span> <span class="discount-price">¥0.00元</span> <span class="original-price">原价:9.00元</span> <span class="buy-now">立即购买</span> </div> </div> </div> <div class="course-item"> <div class="course-image"> <img src="/static/image/course-cover.jpeg" alt=""> </div> <div class="course-info"> <h3>Python开发21天入门 <span><img src="/static/image/avatar1.svg" alt="">100人已加入学习</span></h3> <p class="teather-info">Alex 金角大王 老男孩Python教学总监 <span>共154课时/更新完成</span></p> <ul class="lesson-list"> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码初识编码初识编码</span> <span class="free">免费</span></li> </ul> <div class="pay-box"> <span class="discount-type">限时免费</span> <span class="discount-price">¥0.00元</span> <span class="original-price">原价:9.00元</span> <span class="buy-now">立即购买</span> </div> </div> </div> <div class="course-item"> <div class="course-image"> <img src="/static/image/course-cover.jpeg" alt=""> </div> <div class="course-info"> <h3>Python开发21天入门 <span><img src="/static/image/avatar1.svg" alt="">100人已加入学习</span></h3> <p class="teather-info">Alex 金角大王 老男孩Python教学总监 <span>共154课时/更新完成</span></p> <ul class="lesson-list"> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码初识编码初识编码</span> <span class="free">免费</span></li> </ul> <div class="pay-box"> <span class="discount-type">限时免费</span> <span class="discount-price">¥0.00元</span> <span class="original-price">原价:9.00元</span> <span class="buy-now">立即购买</span> </div> </div> </div> <div class="course-item"> <div class="course-image"> <img src="/static/image/course-cover.jpeg" alt=""> </div> <div class="course-info"> <h3>Python开发21天入门 <span><img src="/static/image/avatar1.svg" alt="">100人已加入学习</span></h3> <p class="teather-info">Alex 金角大王 老男孩Python教学总监 <span>共154课时/更新完成</span></p> <ul class="lesson-list"> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码初识编码初识编码</span> <span class="free">免费</span></li> </ul> <div class="pay-box"> <span class="discount-type">限时免费</span> <span class="discount-price">¥0.00元</span> <span class="original-price">原价:9.00元</span> <span class="buy-now">立即购买</span> </div> </div> </div> </div> </div> <Footer></Footer> </div> </template> <script> import Header from "./common/Header" import Footer from "./common/Footer" export default { name: "Course", data(){ return{ category:0, } }, components:{ Header, Footer, } } </script> <style scoped> .course{ background: #f6f6f6; } .course .main{ width: 1100px; margin: 35px auto 0; } .course .condition{ margin-bottom: 35px; padding: 25px 30px 25px 20px; background: #fff; border-radius: 4px; box-shadow: 0 2px 4px 0 #f0f0f0; } .course .cate-list{ border-bottom: 1px solid #333; border-bottom-color: rgba(51,51,51,.05); padding-bottom: 18px; margin-bottom: 17px; } .course .cate-list::after{ content:""; display: block; clear: both; } .course .cate-list li{ float: left; font-size: 16px; padding: 6px 15px; line-height: 16px; margin-left: 14px; position: relative; transition: all .3s ease; cursor: pointer; color: #4a4a4a; border: 1px solid transparent; /* transparent 透明 */ } .course .cate-list .title{ color: #888; margin-left: 0; letter-spacing: .36px; padding: 0; line-height: 28px; } .course .cate-list .this{ color: #ffc210; border: 1px solid #ffc210!important; border-radius: 30px; } .course .ordering::after{ content:""; display: block; clear: both; } .course .ordering ul{ float: left; } .course .ordering ul::after{ content:""; display: block; clear: both; } .course .ordering .condition-result{ float: right; font-size: 14px; color: #9b9b9b; line-height: 28px; } .course .ordering ul li{ float: left; padding: 6px 15px; line-height: 16px; margin-left: 14px; position: relative; transition: all .3s ease; cursor: pointer; color: #4a4a4a; } .course .ordering .title{ font-size: 16px; color: #888; letter-spacing: .36px; margin-left: 0; padding:0; line-height: 28px; } .course .ordering .this{ color: #ffc210; } .course .ordering .price{ position: relative; } .course .ordering .price::before, .course .ordering .price::after{ cursor: pointer; content:""; display: block; width: 0px; height: 0px; border: 5px solid transparent; position: absolute; right: 0; } .course .ordering .price::before{ border-bottom: 5px solid #aaa; margin-bottom: 2px; top: 2px; } .course .ordering .price::after{ border-top: 5px solid #aaa; bottom: 2px; } .course .course-item:hover{ box-shadow: 4px 6px 16px rgba(0,0,0,.5); } .course .course-item{ width: 1050px; background: #fff; padding: 20px 30px 20px 20px; margin-bottom: 35px; border-radius: 2px; cursor: pointer; box-shadow: 2px 3px 16px rgba(0,0,0,.1); /* css3.0 过渡动画 hover 事件操作 */ transition: all .2s ease; } .course .course-item::after{ content:""; display: block; clear: both; } /* 顶级元素 父级元素 当前元素{} */ .course .course-item .course-image{ float: left; width: 423px; height: 210px; margin-right: 30px; } .course .course-item .course-image img{ width: 100%; } .course .course-item .course-info{ float: left; width: 596px; } .course-item .course-info h3 { font-size: 26px; color: #333; font-weight: normal; margin-bottom: 8px; } .course-item .course-info h3 span{ font-size: 14px; color: #9b9b9b; float: right; margin-top: 14px; } .course-item .course-info h3 span img{ width: 11px; height: auto; margin-right: 7px; } .course-item .course-info .teather-info{ font-size: 14px; color: #9b9b9b; margin-bottom: 14px; padding-bottom: 14px; border-bottom: 1px solid #333; border-bottom-color: rgba(51,51,51,.05); } .course-item .course-info .teather-info span{ float: right; } .course-item .lesson-list::after{ content:""; display: block; clear: both; } .course-item .lesson-list li { float: left; width: 44%; font-size: 14px; color: #666; padding-left: 22px; /* background: url("路径") 是否平铺 x轴位置 y轴位置 */ background: url("/static/image/play-icon-gray.svg") no-repeat left 4px; margin-bottom: 15px; } .course-item .lesson-list li .lesson-title{ /* 以下3句,文本内容过多,会自动隐藏,并显示省略符号 */ text-overflow: ellipsis; overflow: hidden; white-space: nowrap; display:inline-block; max-width: 200px; } .course-item .lesson-list li:hover{ background-image: url("/static/image/play-icon-yellow.svg"); color: #ffc210; } .course-item .lesson-list li .free{ width: 34px; height: 20px; color: #fd7b4d; vertical-align: super; margin-left: 10px; border: 1px solid #fd7b4d; border-radius: 2px; text-align: center; font-size: 13px; white-space: nowrap; } .course-item .lesson-list li:hover .free{ color: #ffc210; border-color: #ffc210; } .course-item .pay-box::after{ content:""; display: block; clear: both; } .course-item .pay-box .discount-type{ padding: 6px 10px; font-size: 16px; color: #fff; text-align: center; margin-right: 8px; background: #fa6240; border: 1px solid #fa6240; border-radius: 10px 0 10px 0; float: left; } .course-item .pay-box .discount-price{ font-size: 24px; color: #fa6240; float: left; } .course-item .pay-box .original-price{ text-decoration: line-through; font-size: 14px; color: #9b9b9b; margin-left: 10px; float: left; margin-top: 10px; } .course-item .pay-box .buy-now{ width: 120px; height: 38px; background: transparent; color: #fa6240; font-size: 16px; border: 1px solid #fd7b4d; border-radius: 3px; transition: all .2s ease-in-out; float: right; text-align: center; line-height: 38px; } .course-item .pay-box .buy-now:hover{ color: #fff; background: #ffc210; border: 1px solid #ffc210; } </style>
路由
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) // @ 表示src目录 import Home from "@/components/Home" import Login from "@/components/Login" import Register from "@/components/Register" import Course from "@/components/Course" export default new Router({ mode:"history", routes: [ // 。。。 { path: '/courses', name: 'Courses', component: Course, } ] })
课程分类:
课程信息:
课程章节:
课时信息:
老师信息:
价格策略:(限时免费\限时折扣\限时满减\原价\优惠券)
在apps下
python ../../manage.py startapp courses
INSTALLED_APPS = [ ... 'courses', ]
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.db import models # Create your models here. from django.db import models from luffyapi.utils.models import BaseModel # Create your models here. class CourseCategory(BaseModel): """ 课程分类 """ name = models.CharField(max_length=64, unique=True, verbose_name="分类名称") class Meta: db_table = "ly_course_category" verbose_name = "课程分类" verbose_name_plural = "课程分类" def __str__(self): return "%s" % self.name class Course(BaseModel): """ 实战课程 """ course_type = ( (0, '付费'), (1, 'VIP专享'), (2, '学位课程'), ) level_choices = ( (0, '初级'), (1, '中级'), (2, '高级'), ) status_choices = ( (0, '上线'), (1, '下线'), (2, '预上线'), ) name = models.CharField(max_length=128, verbose_name="课程名称") course_img = models.ImageField(upload_to="course", max_length=255, verbose_name="封面图片", blank=True, null=True) course_video = models.FileField(upload_to="course_video", max_length=255, verbose_name="封面视频", blank=True, null=True) course_type = models.SmallIntegerField(choices=course_type, default=0, verbose_name="付费类型") # 使用这个字段的原因 brief = models.TextField(verbose_name="详情介绍", null=True, blank=True) level = models.SmallIntegerField(choices=level_choices, default=1, verbose_name="难度等级") pub_date = models.DateField(verbose_name="发布日期", auto_now_add=True) period = models.IntegerField(verbose_name="建议学习周期(day)", default=7) attachment_path = models.FileField(max_length=128, verbose_name="课件路径", blank=True, null=True) status = models.SmallIntegerField(choices=status_choices, default=0, verbose_name="课程状态") course_category = models.ForeignKey("CourseCategory", on_delete=models.CASCADE, null=True, blank=True, verbose_name="课程分类") students = models.IntegerField(verbose_name="学习人数", default=0) lessons = models.IntegerField(verbose_name="总课时数量", default=0) pub_lessons = models.IntegerField(verbose_name="课时更新数量", default=0) price = models.DecimalField(max_digits=6, decimal_places=2, verbose_name="课程原价", default=0) teacher = models.ForeignKey("Teacher", on_delete=models.DO_NOTHING, null=True, blank=True, verbose_name="授课老师") class Meta: db_table = "ly_course" verbose_name = "实战课程" verbose_name_plural = "实战课程" def __str__(self): return "%s" % self.name class Teacher(BaseModel): """讲师、导师表""" role_choices = ( (0, '讲师'), (1, '导师'), (2, '班主任'), ) name = models.CharField(max_length=32, verbose_name="讲师昵称") role = models.SmallIntegerField(choices=role_choices, default=0, verbose_name="讲师身份") title = models.CharField(max_length=64, verbose_name="职位、职称") signature = models.CharField(max_length=255, verbose_name="导师签名", help_text="导师签名", blank=True, null=True) image = models.ImageField(upload_to="teacher",blank=True, null=True, verbose_name="讲师封面") brief = models.TextField(max_length=1024, verbose_name="讲师描述") class Meta: db_table = "ly_teacher" verbose_name = "讲师导师" verbose_name_plural = "讲师导师" def __str__(self): return "%s" % self.name class CourseChapter(BaseModel): """课程章节""" course = models.ForeignKey("Course", related_name='chapters', on_delete=models.CASCADE, verbose_name="课程名称") chapter = models.SmallIntegerField(verbose_name="第几章", default=1) name = models.CharField(max_length=128, verbose_name="章节标题") summary = models.TextField(verbose_name="章节介绍", blank=True, null=True) pub_date = models.DateField(verbose_name="发布日期", auto_now_add=True) class Meta: db_table = "ly_course_chapter" verbose_name = "课程章节" verbose_name_plural = "课程章节" def __str__(self): return "%s:(第%s章)%s" % (self.course, self.chapter, self.name) class CourseLesson(BaseModel): """课程课时""" lesson_type_choices = ( (0, '文档'), (1, '练习'), (2, '视频') ) chapter = models.ForeignKey("CourseChapter", related_name='lessons', on_delete=models.CASCADE, verbose_name="章节") course = models.ForeignKey("Course", related_name="lesson_list", on_delete=models.CASCADE, verbose_name="课程") name = models.CharField(max_length=128, verbose_name="课时标题") lesson_type = models.SmallIntegerField(default=2, choices=lesson_type_choices, verbose_name="课时种类") lesson_link = models.CharField(max_length=255, blank=True, null=True, verbose_name="课时链接", help_text="若是video,填vid,若是文档,填link") duration = models.CharField(verbose_name="视频时长", blank=True, null=True, max_length=32) # 仅在前端展示使用 pub_date = models.DateTimeField(verbose_name="发布时间", auto_now_add=True) free_trail = models.BooleanField(verbose_name="是否可试看", default=False) recomment = models.BooleanField(verbose_name="是否推荐到课程列表") class Meta: db_table = "ly_course_lesson" verbose_name = "课程课时" verbose_name_plural = "课程课时" def __str__(self): return "%s-%s" % (self.chapter, self.name)
python manage.py makemigrations
python manage.py migrate
把当前新增的课程模型注册到xadmin里面.
coursers/adminx.py,代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import xadmin from .models import CourseCategory class CourseCategoryModelAdmin(object): """课程分类模型管理类""" pass xadmin.site.register(CourseCategory, CourseCategoryModelAdmin) from .models import Course class CourseModelAdmin(object): """课程模型管理类""" pass xadmin.site.register(Course, CourseModelAdmin) from .models import Teacher class TeacherModelAdmin(object): """老师模型管理类""" pass xadmin.site.register(Teacher, TeacherModelAdmin) from .models import CourseChapter class CourseChapterModelAdmin(object): """课程章节模型管理类""" pass xadmin.site.register(CourseChapter, CourseChapterModelAdmin) from .models import CourseLesson class CourseLessonModelAdmin(object): """课程课时模型管理类""" pass xadmin.site.register(CourseLesson, CourseLessonModelAdmin)
-
-
可以采用第三方模块Faker来完成数据的模拟添加
-
可以使用python脚本或者shell脚本来完成
这里我们学习第三种方法.那么,我们就要学习怎么编写一个python终端脚本或者shell脚本。
要编写一个python或者shell脚本,就要清楚一件事情,就是我们可以根据对应的语言来编写对应的终端代码,但是必须在首行的位置声明执行这些代码的解析器是谁?
shell(介绍)
#! /usr/bin/python3 # 注释,后续的代码必须要符合python的语法 print("hello world")
#! /bin/bash # 注释,后续的代码必须要符合shell的语法,或者可以填写linux命令,例如,chmod,cd, copy
编写完成脚本以后,脚本本身因为操作系统默认会取消它的执行权限,所以我们通过以下命令来增加执行的权限
chmod +x 对应的文件名 # 例如:有一个python脚本在桌面,我们需要赋予执行的权限。文件名假设为:demo.py cd ~/Desktop chmod +x demo.py # 例如:有一个shell脚本在桌面,我们需要赋予执行的权限,文件名假设为:demo.sh cd ~/Desktop chmod +x demo.sh
赋予了权限以后,就可以执行脚本了。
# 例如,上面的demo.py cd ~/Desktop ./demo.py
1. 编写一个sql语句的文件test_data.sql
# 关闭原来表中的主外键约束功能 set FOREIGN_KEY_CHECKS=0; # 清空原有的课程分类表信息 truncate table ly_course_category; # 添加导航信息 insert into ly_course_category (name,orders,is_show,is_delete,create_time,update_time) VALUES ("python",1,1,0,"2019-11-11 12:00:00","2019-11-11 12:00:00"), ("python进阶",2,1,0,"2019-11-11 12:00:00","2019-11-11 12:00:00"), ("java",3,1,0,"2019-11-11 12:00:00","2019-11-11 12:00:00"), ("前端开发",4,1,0,"2019-11-11 12:00:00","2019-11-11 12:00:00"); # 开启原来表中的主外键约束功能 set FOREIGN_KEY_CHECKS=1;
2. 编写一个shell脚本test_data.sh来执行上面的文件
#! /bin/bash mysql -uroot -p456 luffy < ./test_data.sql
3. 赋予create_data.sh执行的权限
chmod +x test_data.sh
创建序列化器
from rest_framework import serializers from .models import CourseCategory class CourseCategoryModelSerializer(serializers.ModelSerializer): class Meta: model = CourseCategory fields = ["id","name"]
courses/views.py
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from rest_framework.generics import ListAPIView from .models import CourseCategory from .serializers import CourseCategoryModelSerializer class CourseCategoryListAPIView(ListAPIView): queryset = CourseCategory.objects.filter(is_show=True, is_delete=False).order_by("orders","-id") serializer_class = CourseCategoryModelSerializer # 设置不分页,提前写这段代码的作用就是防止将来如果进行全局分页,可以不被它干扰到 pagination_class = None
# 子应用路由 from django.urls import path from . import views urlpatterns = [ path("category/",views.CourseCategoryListAPIView.as_view()), ] # 总路由 path('courses/', include("courses.urls") ),
course
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<template> <div class="course"> <Header></Header> <div class="main"> <!-- 筛选条件 --> <div class="condition"> <ul class="cate-list"> <li class="title">课程分类:</li> <li class="this">全部</li> <li v-for="category in category_list">{{category.name}}</li> </ul> <div class="ordering"> <ul> <li class="title">筛 选: </li> <li class="default this">默认</li> <li class="hot this">人气</li> <li class="price this">价格</li> </ul> <p class="condition-result">共21个课程</p> </div> </div> <!-- 课程列表 --> <div class="course-list"> <div class="course-item"> <div class="course-image"> <img src="/static/image/course-cover.jpeg" alt=""> </div> <div class="course-info"> <h3><router-link to="/course/detail/1">Python开发21天入门</router-link> <span><img src="/static/image/avatar1.svg" alt="">100人已加入学习</span></h3> <p class="teather-info">Alex 金角大王 老男孩Python教学总监 <span>共154课时/更新完成</span></p> <ul class="lesson-list"> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码初识编码初识编码</span> <span class="free">免费</span></li> </ul> <div class="pay-box"> <span class="discount-type">限时免费</span> <span class="discount-price">¥0.00元</span> <span class="original-price">原价:9.00元</span> <span class="buy-now">立即购买</span> </div> </div> </div> <div class="course-item"> <div class="course-image"> <img src="/static/image/course-cover.jpeg" alt=""> </div> <div class="course-info"> <h3>Python开发21天入门 <span><img src="/static/image/avatar1.svg" alt="">100人已加入学习</span></h3> <p class="teather-info">Alex 金角大王 老男孩Python教学总监 <span>共154课时/更新完成</span></p> <ul class="lesson-list"> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码初识编码初识编码</span> <span class="free">免费</span></li> </ul> <div class="pay-box"> <span class="discount-type">限时免费</span> <span class="discount-price">¥0.00元</span> <span class="original-price">原价:9.00元</span> <span class="buy-now">立即购买</span> </div> </div> </div> <div class="course-item"> <div class="course-image"> <img src="/static/image/course-cover.jpeg" alt=""> </div> <div class="course-info"> <h3>Python开发21天入门 <span><img src="/static/image/avatar1.svg" alt="">100人已加入学习</span></h3> <p class="teather-info">Alex 金角大王 老男孩Python教学总监 <span>共154课时/更新完成</span></p> <ul class="lesson-list"> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码初识编码初识编码</span> <span class="free">免费</span></li> </ul> <div class="pay-box"> <span class="discount-type">限时免费</span> <span class="discount-price">¥0.00元</span> <span class="original-price">原价:9.00元</span> <span class="buy-now">立即购买</span> </div> </div> </div> <div class="course-item"> <div class="course-image"> <img src="/static/image/course-cover.jpeg" alt=""> </div> <div class="course-info"> <h3>Python开发21天入门 <span><img src="/static/image/avatar1.svg" alt="">100人已加入学习</span></h3> <p class="teather-info">Alex 金角大王 老男孩Python教学总监 <span>共154课时/更新完成</span></p> <ul class="lesson-list"> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码初识编码初识编码</span> <span class="free">免费</span></li> </ul> <div class="pay-box"> <span class="discount-type">限时免费</span> <span class="discount-price">¥0.00元</span> <span class="original-price">原价:9.00元</span> <span class="buy-now">立即购买</span> </div> </div> </div> </div> </div> <Footer></Footer> </div> </template> <script> import Header from "./common/Header" import Footer from "./common/Footer" export default { name: "Course", data(){ return{ category:0, category_list: [], } }, created(){ this.get_course_category(); }, methods:{ get_course_category(){ // 获取课程分类 this.$axios.get(`${this.$settings.Host}/courses/category/`).then(response=>{ this.category_list = response.data; }).catch(error=>{ this.$message.error("无法获取课程分类信息!"); }) } }, components:{ Header, Footer, } } </script> <style scoped> .course{ background: #f6f6f6; } .course .main{ width: 1100px; margin: 35px auto 0; } .course .condition{ margin-bottom: 35px; padding: 25px 30px 25px 20px; background: #fff; border-radius: 4px; box-shadow: 0 2px 4px 0 #f0f0f0; } .course .cate-list{ border-bottom: 1px solid #333; border-bottom-color: rgba(51,51,51,.05); padding-bottom: 18px; margin-bottom: 17px; } .course .cate-list::after{ content:""; display: block; clear: both; } .course .cate-list li{ float: left; font-size: 16px; padding: 6px 15px; line-height: 16px; margin-left: 14px; position: relative; transition: all .3s ease; cursor: pointer; color: #4a4a4a; border: 1px solid transparent; /* transparent 透明 */ } .course .cate-list .title{ color: #888; margin-left: 0; letter-spacing: .36px; padding: 0; line-height: 28px; } .course .cate-list .this{ color: #ffc210; border: 1px solid #ffc210!important; border-radius: 30px; } .course .ordering::after{ content:""; display: block; clear: both; } .course .ordering ul{ float: left; } .course .ordering ul::after{ content:""; display: block; clear: both; } .course .ordering .condition-result{ float: right; font-size: 14px; color: #9b9b9b; line-height: 28px; } .course .ordering ul li{ float: left; padding: 6px 15px; line-height: 16px; margin-left: 14px; position: relative; transition: all .3s ease; cursor: pointer; color: #4a4a4a; } .course .ordering .title{ font-size: 16px; color: #888; letter-spacing: .36px; margin-left: 0; padding:0; line-height: 28px; } .course .ordering .this{ color: #ffc210; } .course .ordering .price{ position: relative; } .course .ordering .price::before, .course .ordering .price::after{ cursor: pointer; content:""; display: block; width: 0px; height: 0px; border: 5px solid transparent; position: absolute; right: 0; } .course .ordering .price::before{ border-bottom: 5px solid #aaa; margin-bottom: 2px; top: 2px; } .course .ordering .price::after{ border-top: 5px solid #aaa; bottom: 2px; } .course .course-item:hover{ box-shadow: 4px 6px 16px rgba(0,0,0,.5); } .course .course-item{ width: 1050px; background: #fff; padding: 20px 30px 20px 20px; margin-bottom: 35px; border-radius: 2px; cursor: pointer; box-shadow: 2px 3px 16px rgba(0,0,0,.1); /* css3.0 过渡动画 hover 事件操作 */ transition: all .2s ease; } .course .course-item::after{ content:""; display: block; clear: both; } /* 顶级元素 父级元素 当前元素{} */ .course .course-item .course-image{ float: left; width: 423px; height: 210px; margin-right: 30px; } .course .course-item .course-image img{ width: 100%; } .course .course-item .course-info{ float: left; width: 596px; } .course-item .course-info h3 { font-size: 26px; color: #333; font-weight: normal; margin-bottom: 8px; } .course-item .course-info h3 span{ font-size: 14px; color: #9b9b9b; float: right; margin-top: 14px; } .course-item .course-info h3 span img{ width: 11px; height: auto; margin-right: 7px; } .course-item .course-info .teather-info{ font-size: 14px; color: #9b9b9b; margin-bottom: 14px; padding-bottom: 14px; border-bottom: 1px solid #333; border-bottom-color: rgba(51,51,51,.05); } .course-item .course-info .teather-info span{ float: right; } .course-item .lesson-list::after{ content:""; display: block; clear: both; } .course-item .lesson-list li { float: left; width: 44%; font-size: 14px; color: #666; padding-left: 22px; /* background: url("路径") 是否平铺 x轴位置 y轴位置 */ background: url("/static/image/play-icon-gray.svg") no-repeat left 4px; margin-bottom: 15px; } .course-item .lesson-list li .lesson-title{ /* 以下3句,文本内容过多,会自动隐藏,并显示省略符号 */ text-overflow: ellipsis; overflow: hidden; white-space: nowrap; display:inline-block; max-width: 200px; } .course-item .lesson-list li:hover{ background-image: url("/static/image/play-icon-yellow.svg"); color: #ffc210; } .course-item .lesson-list li .free{ width: 34px; height: 20px; color: #fd7b4d; vertical-align: super; margin-left: 10px; border: 1px solid #fd7b4d; border-radius: 2px; text-align: center; font-size: 13px; white-space: nowrap; } .course-item .lesson-list li:hover .free{ color: #ffc210; border-color: #ffc210; } .course-item .pay-box::after{ content:""; display: block; clear: both; } .course-item .pay-box .discount-type{ padding: 6px 10px; font-size: 16px; color: #fff; text-align: center; margin-right: 8px; background: #fa6240; border: 1px solid #fa6240; border-radius: 10px 0 10px 0; float: left; } .course-item .pay-box .discount-price{ font-size: 24px; color: #fa6240; float: left; } .course-item .pay-box .original-price{ text-decoration: line-through; font-size: 14px; color: #9b9b9b; margin-left: 10px; float: left; margin-top: 10px; } .course-item .pay-box .buy-now{ width: 120px; height: 38px; background: transparent; color: #fa6240; font-size: 16px; border: 1px solid #fd7b4d; border-radius: 3px; transition: all .2s ease-in-out; float: right; text-align: center; line-height: 38px; } .course-item .pay-box .buy-now:hover{ color: #fff; background: #ffc210; border: 1px solid #ffc210; } </style>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<template> <div class="course"> <Header></Header> <div class="main"> <!-- 筛选条件 --> <div class="condition"> <ul class="cate-list"> <li class="title">课程分类:</li> <li :class="category==0?'this':''" @click="category=0">全部</li> <li :class="category==item.id?'this':''" v-for="item in category_list" @click="category=item.id">{{item.name}}</li> </ul> <div class="ordering"> <ul> <li class="title">筛 选: </li> <li class="default this">默认</li> <li class="hot this">人气</li> <li class="price this">价格</li> </ul> <p class="condition-result">共21个课程</p> </div> </div> <!-- 课程列表 --> <div class="course-list"> <div class="course-item"> <div class="course-image"> <img src="/static/image/course-cover.jpeg" alt=""> </div> <div class="course-info"> <h3><router-link to="/course/detail/1">Python开发21天入门</router-link> <span><img src="/static/image/avatar1.svg" alt="">100人已加入学习</span></h3> <p class="teather-info">Alex 金角大王 老男孩Python教学总监 <span>共154课时/更新完成</span></p> <ul class="lesson-list"> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码初识编码初识编码</span> <span class="free">免费</span></li> </ul> <div class="pay-box"> <span class="discount-type">限时免费</span> <span class="discount-price">¥0.00元</span> <span class="original-price">原价:9.00元</span> <span class="buy-now">立即购买</span> </div> </div> </div> <div class="course-item"> <div class="course-image"> <img src="/static/image/course-cover.jpeg" alt=""> </div> <div class="course-info"> <h3>Python开发21天入门 <span><img src="/static/image/avatar1.svg" alt="">100人已加入学习</span></h3> <p class="teather-info">Alex 金角大王 老男孩Python教学总监 <span>共154课时/更新完成</span></p> <ul class="lesson-list"> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码初识编码初识编码</span> <span class="free">免费</span></li> </ul> <div class="pay-box"> <span class="discount-type">限时免费</span> <span class="discount-price">¥0.00元</span> <span class="original-price">原价:9.00元</span> <span class="buy-now">立即购买</span> </div> </div> </div> <div class="course-item"> <div class="course-image"> <img src="/static/image/course-cover.jpeg" alt=""> </div> <div class="course-info"> <h3>Python开发21天入门 <span><img src="/static/image/avatar1.svg" alt="">100人已加入学习</span></h3> <p class="teather-info">Alex 金角大王 老男孩Python教学总监 <span>共154课时/更新完成</span></p> <ul class="lesson-list"> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码初识编码初识编码</span> <span class="free">免费</span></li> </ul> <div class="pay-box"> <span class="discount-type">限时免费</span> <span class="discount-price">¥0.00元</span> <span class="original-price">原价:9.00元</span> <span class="buy-now">立即购买</span> </div> </div> </div> <div class="course-item"> <div class="course-image"> <img src="/static/image/course-cover.jpeg" alt=""> </div> <div class="course-info"> <h3>Python开发21天入门 <span><img src="/static/image/avatar1.svg" alt="">100人已加入学习</span></h3> <p class="teather-info">Alex 金角大王 老男孩Python教学总监 <span>共154课时/更新完成</span></p> <ul class="lesson-list"> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码初识编码初识编码</span> <span class="free">免费</span></li> </ul> <div class="pay-box"> <span class="discount-type">限时免费</span> <span class="discount-price">¥0.00元</span> <span class="original-price">原价:9.00元</span> <span class="buy-now">立即购买</span> </div> </div> </div> </div> </div> <Footer></Footer> </div> </template> <script> import Header from "./common/Header" import Footer from "./common/Footer" export default { name: "Course", data(){ return{ category: 0, // 当前点击的课程分类ID,0表示默认值,全部 category_list: [], } }, created(){ this.get_course_category(); }, methods:{ get_course_category(){ // 获取课程分类 this.$axios.get(`${this.$settings.Host}/courses/category/`).then(response=>{ this.category_list = response.data; }).catch(error=>{ this.$message.error("无法获取课程分类信息!"); }) } }, components:{ Header, Footer, } } </script> <style scoped> .course{ background: #f6f6f6; } .course .main{ width: 1100px; margin: 35px auto 0; } .course .condition{ margin-bottom: 35px; padding: 25px 30px 25px 20px; background: #fff; border-radius: 4px; box-shadow: 0 2px 4px 0 #f0f0f0; } .course .cate-list{ border-bottom: 1px solid #333; border-bottom-color: rgba(51,51,51,.05); padding-bottom: 18px; margin-bottom: 17px; } .course .cate-list::after{ content:""; display: block; clear: both; } .course .cate-list li{ float: left; font-size: 16px; padding: 6px 15px; line-height: 16px; margin-left: 14px; position: relative; transition: all .3s ease; cursor: pointer; color: #4a4a4a; border: 1px solid transparent; /* transparent 透明 */ } .course .cate-list .title{ color: #888; margin-left: 0; letter-spacing: .36px; padding: 0; line-height: 28px; } .course .cate-list .this{ color: #ffc210; border: 1px solid #ffc210!important; border-radius: 30px; } .course .ordering::after{ content:""; display: block; clear: both; } .course .ordering ul{ float: left; } .course .ordering ul::after{ content:""; display: block; clear: both; } .course .ordering .condition-result{ float: right; font-size: 14px; color: #9b9b9b; line-height: 28px; } .course .ordering ul li{ float: left; padding: 6px 15px; line-height: 16px; margin-left: 14px; position: relative; transition: all .3s ease; cursor: pointer; color: #4a4a4a; } .course .ordering .title{ font-size: 16px; color: #888; letter-spacing: .36px; margin-left: 0; padding:0; line-height: 28px; } .course .ordering .this{ color: #ffc210; } .course .ordering .price{ position: relative; } .course .ordering .price::before, .course .ordering .price::after{ cursor: pointer; content:""; display: block; width: 0px; height: 0px; border: 5px solid transparent; position: absolute; right: 0; } .course .ordering .price::before{ border-bottom: 5px solid #aaa; margin-bottom: 2px; top: 2px; } .course .ordering .price::after{ border-top: 5px solid #aaa; bottom: 2px; } .course .course-item:hover{ box-shadow: 4px 6px 16px rgba(0,0,0,.5); } .course .course-item{ width: 1050px; background: #fff; padding: 20px 30px 20px 20px; margin-bottom: 35px; border-radius: 2px; cursor: pointer; box-shadow: 2px 3px 16px rgba(0,0,0,.1); /* css3.0 过渡动画 hover 事件操作 */ transition: all .2s ease; } .course .course-item::after{ content:""; display: block; clear: both; } /* 顶级元素 父级元素 当前元素{} */ .course .course-item .course-image{ float: left; width: 423px; height: 210px; margin-right: 30px; } .course .course-item .course-image img{ width: 100%; } .course .course-item .course-info{ float: left; width: 596px; } .course-item .course-info h3 { font-size: 26px; color: #333; font-weight: normal; margin-bottom: 8px; } .course-item .course-info h3 span{ font-size: 14px; color: #9b9b9b; float: right; margin-top: 14px; } .course-item .course-info h3 span img{ width: 11px; height: auto; margin-right: 7px; } .course-item .course-info .teather-info{ font-size: 14px; color: #9b9b9b; margin-bottom: 14px; padding-bottom: 14px; border-bottom: 1px solid #333; border-bottom-color: rgba(51,51,51,.05); } .course-item .course-info .teather-info span{ float: right; } .course-item .lesson-list::after{ content:""; display: block; clear: both; } .course-item .lesson-list li { float: left; width: 44%; font-size: 14px; color: #666; padding-left: 22px; /* background: url("路径") 是否平铺 x轴位置 y轴位置 */ background: url("/static/image/play-icon-gray.svg") no-repeat left 4px; margin-bottom: 15px; } .course-item .lesson-list li .lesson-title{ /* 以下3句,文本内容过多,会自动隐藏,并显示省略符号 */ text-overflow: ellipsis; overflow: hidden; white-space: nowrap; display:inline-block; max-width: 200px; } .course-item .lesson-list li:hover{ background-image: url("/static/image/play-icon-yellow.svg"); color: #ffc210; } .course-item .lesson-list li .free{ width: 34px; height: 20px; color: #fd7b4d; vertical-align: super; margin-left: 10px; border: 1px solid #fd7b4d; border-radius: 2px; text-align: center; font-size: 13px; white-space: nowrap; } .course-item .lesson-list li:hover .free{ color: #ffc210; border-color: #ffc210; } .course-item .pay-box::after{ content:""; display: block; clear: both; } .course-item .pay-box .discount-type{ padding: 6px 10px; font-size: 16px; color: #fff; text-align: center; margin-right: 8px; background: #fa6240; border: 1px solid #fa6240; border-radius: 10px 0 10px 0; float: left; } .course-item .pay-box .discount-price{ font-size: 24px; color: #fa6240; float: left; } .course-item .pay-box .original-price{ text-decoration: line-through; font-size: 14px; color: #9b9b9b; margin-left: 10px; float: left; margin-top: 10px; } .course-item .pay-box .buy-now{ width: 120px; height: 38px; background: transparent; color: #fa6240; font-size: 16px; border: 1px solid #fd7b4d; border-radius: 3px; transition: all .2s ease-in-out; float: right; text-align: center; line-height: 38px; } .course-item .pay-box .buy-now:hover{ color: #fff; background: #ffc210; border: 1px solid #ffc210; } </style>
序列化器,代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from rest_framework import serializers from .models import CourseCategory class CourseCategoryModelSerializer(serializers.ModelSerializer): class Meta: model = CourseCategory fields = ["id","name"] from .models import Course class CourseModelSerializer(serializers.ModelSerializer): """课程""" class Meta: model = Course fields = ["id","name","course_img","students","lessons","pub_lessons","price","teacher"]
视图代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# Create your views here. from rest_framework.generics import ListAPIView from .models import CourseCategory,Course from .serializers import CourseCategoryModelSerializer,CourseModelSerializer class CourseCategoryListAPIView(ListAPIView): """课程分类列表接口""" // .... class CourseListAPIView(ListAPIView): """课程列表""" queryset = Course.objects.filter(is_show=True, is_delete=False).order_by("orders", "-id") serializer_class = CourseModelSerializer
路由:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 子应用路由 from django.urls import path,re_path from . import views urlpatterns = [ path("category/",views.CourseCategoryListAPIView.as_view()), path("", views.CourseListAPIView.as_view()), ]
访问效果
上面虽然返回了课程基本信息,但是这里Teacher字段返回的是一个模型对象,这个模型对象被作为字符串输出时,默认输出的是主键ID,所以我们接下来需要对这个外检字段Teacher进行重新调整,让他可以输出老师的其他信息,而不仅是主键ID。
这里有两种解决方案:
1.在模型中通过给模型增加自定义字段方法来返回多个字段数据
# 模型代码: class Course(BaseModel): @property def teacher_name(self): return self.teacher.name # 序列化器代码: class CourseModelSerializer(serializers.ModelSerializer): """课程""" class Meta: model = Course fields = ["id","name","course_img","students","lessons","pub_lessons","price","teacher","teacher_name"]
2.
from .models import CourseCategory,Course,Teacher class TeacherModelSerializer(serializers.ModelSerializer): """课程列表的老师信息""" class Meta: model = Teacher fields = ["id","name","title","signature"] class CourseModelSerializer(serializers.ModelSerializer): """课程列表的课程基本信息""" # 序列化器嵌套[被嵌套的序列化器必须声明对应的字段为模型原有的外键字段,同时这个被嵌套的序列化器必须先声明才能进行调用!] # 如果嵌套的序列化器数据有多条,则需要在调用序列化器时需要声明 many=True teacher = TeacherModelSerializer() class Meta: model = Course fields = ["id","name","course_img","students","lessons","pub_lessons","price","teacher"]
服务端提供role_name字段,models.py代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Teacher(BaseModel): """讲师、导师表""" role_choices = ( (0, '讲师'), (1, '导师'), (2, '班主任'), ) name = models.CharField(max_length=32, verbose_name="讲师昵称") role = models.SmallIntegerField(choices=role_choices, default=0, verbose_name="讲师身份") title = models.CharField(max_length=64, verbose_name="职位、职称") signature = models.CharField(max_length=255, verbose_name="导师签名", help_text="导师签名", blank=True, null=True) image = models.ImageField(upload_to="teacher", null=True, verbose_name = "讲师封面") brief = models.TextField(max_length=1024, verbose_name="讲师描述") class Meta: db_table = "ly_teacher" verbose_name = "讲师导师" verbose_name_plural = "讲师导师" @property def role_name(self): return self.role_choices[self.role][1]
serializers.py
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from .models import Teacher class TeacherModelSerializer(serializers.ModelSerializer): """讲师导师序列化器""" class Meta: model = Teacher fields = ["id","name","role_name","title","signature"]
Course.vue,代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<template> <div class="course"> <Header></Header> <div class="main"> <!-- 筛选条件 --> <div class="condition"> <ul class="cate-list"> <li class="title">课程分类:</li> <li :class="category==0?'this':''" @click="category=0">全部</li> <li :class="category==item.id?'this':''" v-for="item in category_list" @click="category=item.id">{{item.name}}</li> </ul> <div class="ordering"> <ul> <li class="title">筛 选: </li> <li class="default this">默认</li> <li class="hot this">人气</li> <li class="price this">价格</li> </ul> <p class="condition-result">共21个课程</p> </div> </div> <!-- 课程列表 --> <div class="course-list"> <div class="course-item" v-for="course in course_list"> <div class="course-image"> <img :src="course.course_img" alt=""> </div> <div class="course-info"> <h3><router-link to="/course/detail/1">{{course.name}}</router-link> <span><img src="/static/image/avatar1.svg" alt="">{{course.students}}人已加入学习</span></h3> <p class="teather-info">{{course.teacher.role_name}} {{course.teacher.name}} {{course.teacher.signature}} {{course.teacher.title}} <span>共{{course.lessons}}课时/{{course.lessons==course.pub_lessons?'更新完成':'已更新'+course.pub_lessons+'课时'}}</span></p> <ul class="lesson-list"> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码</span> <span class="free">免费</span></li> <li><span class="lesson-title">01 | 第1节:初识编码初识编码初识编码初识编码</span> <span class="free">免费</span></li> </ul> <div class="pay-box"> <span class="discount-type">限时免费</span> <span class="discount-price">¥0.00元</span> <span class="original-price">原价:{{course.price}}元</span> <span class="buy-now">立即购买</span> </div> </div> </div> </div> </div> <Footer></Footer> </div> </template> <script> import Header from "./common/Header" import Footer from "./common/Footer" export default { name: "Course", data(){ return{ category: 0, // 当前点击的课程分类ID,0表示默认值,全部 category_list: [], // 课程分类列表 course_list: [ { teacher: {}, } ], } }, created(){ this.get_course_category(); this.get_course(); }, methods:{ get_course_category(){ // 获取课程分类 this.$axios.get(`${this.$settings.Host}/courses/category/`).then(response=>{ this.category_list = response.data; }).catch(error=>{ this.$message.error("无法获取课程分类信息!"); }) }, get_course(){ // 获取课程信息 this.$axios.get(`${this.$settings.Host}/courses/`).then(response=>{ this.course_list = response.data; }).catch(error=>{ this.$message.error("无法获取课程信息!"); }) } }, components:{ Header, Footer, } } </script> <style scoped> .course{ background: #f6f6f6; } .course .main{ width: 1100px; margin: 35px auto 0; } .course .condition{ margin-bottom: 35px; padding: 25px 30px 25px 20px; background: #fff; border-radius: 4px; box-shadow: 0 2px 4px 0 #f0f0f0; } .course .cate-list{ border-bottom: 1px solid #333; border-bottom-color: rgba(51,51,51,.05); padding-bottom: 18px; margin-bottom: 17px; } .course .cate-list::after{ content:""; display: block; clear: both; } .course .cate-list li{ float: left; font-size: 16px; padding: 6px 15px; line-height: 16px; margin-left: 14px; position: relative; transition: all .3s ease; cursor: pointer; color: #4a4a4a; border: 1px solid transparent; /* transparent 透明 */ } .course .cate-list .title{ color: #888; margin-left: 0; letter-spacing: .36px; padding: 0; line-height: 28px; } .course .cate-list .this{ color: #ffc210; border: 1px solid #ffc210!important; border-radius: 30px; } .course .ordering::after{ content:""; display: block; clear: both; } .course .ordering ul{ float: left; } .course .ordering ul::after{ content:""; display: block; clear: both; } .course .ordering .condition-result{ float: right; font-size: 14px; color: #9b9b9b; line-height: 28px; } .course .ordering ul li{ float: left; padding: 6px 15px; line-height: 16px; margin-left: 14px; position: relative; transition: all .3s ease; cursor: pointer; color: #4a4a4a; } .course .ordering .title{ font-size: 16px; color: #888; letter-spacing: .36px; margin-left: 0; padding:0; line-height: 28px; } .course .ordering .this{ color: #ffc210; } .course .ordering .price{ position: relative; } .course .ordering .price::before, .course .ordering .price::after{ cursor: pointer; content:""; display: block; width: 0px; height: 0px; border: 5px solid transparent; position: absolute; right: 0; } .course .ordering .price::before{ border-bottom: 5px solid #aaa; margin-bottom: 2px; top: 2px; } .course .ordering .price::after{ border-top: 5px solid #aaa; bottom: 2px; } .course .course-item:hover{ box-shadow: 4px 6px 16px rgba(0,0,0,.5); } .course .course-item{ width: 1050px; background: #fff; padding: 20px 30px 20px 20px; margin-bottom: 35px; border-radius: 2px; cursor: pointer; box-shadow: 2px 3px 16px rgba(0,0,0,.1); /* css3.0 过渡动画 hover 事件操作 */ transition: all .2s ease; } .course .course-item::after{ content:""; display: block; clear: both; } /* 顶级元素 父级元素 当前元素{} */ .course .course-item .course-image{ float: left; width: 423px; height: 210px; margin-right: 30px; } .course .course-item .course-image img{ width: 100%; } .course .course-item .course-info{ float: left; width: 596px; } .course-item .course-info h3 { font-size: 26px; color: #333; font-weight: normal; margin-bottom: 8px; } .course-item .course-info h3 span{ font-size: 14px; color: #9b9b9b; float: right; margin-top: 14px; } .course-item .course-info h3 span img{ width: 11px; height: auto; margin-right: 7px; } .course-item .course-info .teather-info{ font-size: 14px; color: #9b9b9b; margin-bottom: 14px; padding-bottom: 14px; border-bottom: 1px solid #333; border-bottom-color: rgba(51,51,51,.05); } .course-item .course-info .teather-info span{ float: right; } .course-item .lesson-list::after{ content:""; display: block; clear: both; } .course-item .lesson-list li { float: left; width: 44%; font-size: 14px; color: #666; padding-left: 22px; /* background: url("路径") 是否平铺 x轴位置 y轴位置 */ background: url("/static/image/play-icon-gray.svg") no-repeat left 4px; margin-bottom: 15px; } .course-item .lesson-list li .lesson-title{ /* 以下3句,文本内容过多,会自动隐藏,并显示省略符号 */ text-overflow: ellipsis; overflow: hidden; white-space: nowrap; display:inline-block; max-width: 200px; } .course-item .lesson-list li:hover{ background-image: url("/static/image/play-icon-yellow.svg"); color: #ffc210; } .course-item .lesson-list li .free{ width: 34px; height: 20px; color: #fd7b4d; vertical-align: super; margin-left: 10px; border: 1px solid #fd7b4d; border-radius: 2px; text-align: center; font-size: 13px; white-space: nowrap; } .course-item .lesson-list li:hover .free{ color: #ffc210; border-color: #ffc210; } .course-item .pay-box::after{ content:""; display: block; clear: both; } .course-item .pay-box .discount-type{ padding: 6px 10px; font-size: 16px; color: #fff; text-align: center; margin-right: 8px; background: #fa6240; border: 1px solid #fa6240; border-radius: 10px 0 10px 0; float: left; } .course-item .pay-box .discount-price{ font-size: 24px; color: #fa6240; float: left; } .course-item .pay-box .original-price{ text-decoration: line-through; font-size: 14px; color: #9b9b9b; margin-left: 10px; float: left; margin-top: 10px; } .course-item .pay-box .buy-now{ width: 120px; height: 38px; background: transparent; color: #fa6240; font-size: 16px; border: 1px solid #fd7b4d; border-radius: 3px; transition: all .2s ease-in-out; float: right; text-align: center; line-height: 38px; } .course-item .pay-box .buy-now:hover{ color: #fff; background: #ffc210; border: 1px solid #ffc210; } </style>
客户端的课程列表显示当前课程的章节
可以通过序列化器嵌套来完成,但是查询过程的数量不好控制。以下代码仅供参考
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from .models import Course class CourseModelSerializer(serializers.ModelSerializer): """课程""" teacher = TeacherModelSerializer() class Meta: model = Course fields = ["id","name","course_img","students","lessons","pub_lessons","price","teacher","recomment_lessons"]
models
增加方法 recomment_lessons
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Course(BaseModel): """ 实战课程 """ course_type = ( (0, '付费'), (1, 'VIP专享'), (2, '学位课程'), ) level_choices = ( (0, '初级'), (1, '中级'), (2, '高级'), ) status_choices = ( (0, '上线'), (1, '下线'), (2, '预上线'), ) name = models.CharField(max_length=128, verbose_name="课程名称") course_img = models.ImageField(upload_to="course", max_length=255, verbose_name="封面图片", blank=True, null=True) course_video = models.FileField(upload_to="course_video", max_length=255, verbose_name="封面视频", blank=True, null=True) course_type = models.SmallIntegerField(choices=course_type, default=0, verbose_name="付费类型") # 使用这个字段的原因 brief = models.TextField(verbose_name="详情介绍", null=True, blank=True) level = models.SmallIntegerField(choices=level_choices, default=1, verbose_name="难度等级") pub_date = models.DateField(verbose_name="发布日期", auto_now_add=True) period = models.IntegerField(verbose_name="建议学习周期(day)", default=7) attachment_path = models.FileField(max_length=128, verbose_name="课件路径", blank=True, null=True) status = models.SmallIntegerField(choices=status_choices, default=0, verbose_name="课程状态") course_category = models.ForeignKey("CourseCategory", on_delete=models.CASCADE, null=True, blank=True, verbose_name="课程分类") students = models.IntegerField(verbose_name="学习人数", default=0) lessons = models.IntegerField(verbose_name="总课时数量", default=0) pub_lessons = models.IntegerField(verbose_name="课时更新数量", default=0) price = models.DecimalField(max_digits=6, decimal_places=2, verbose_name="课程原价", default=0) teacher = models.ForeignKey("Teacher", on_delete=models.DO_NOTHING, null=True, blank=True, verbose_name="授课老师") class Meta: db_table = "ly_course" verbose_name = "实战课程" verbose_name_plural = "实战课程" def teacher_name(self): return self.teacher.name @property def recomment_lessons(self): """课程列表的推荐课时""" lesson_list = self.lesson_list.filter(recomment=True, is_show=True, is_delete=False).order_by("orders","id") print(lesson_list,111111) # data = [] # for lesson in lesson_list: # data.append({ # "id": lesson.id, # "name": lesson.name, # "free_trail": lesson.free_trail, # }) # return data # 列表生成式 return [{"id":lesson.id, "name": lesson.name, "free_trail": lesson.free_trail} for lesson in lesson_list] def __str__(self): return "%s" % self.name
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<template> <div class="course"> <Header></Header> <div class="main"> <!-- 筛选条件 --> <div class="condition"> <ul class="cate-list"> <li class="title">课程分类:</li> <li :class="category==0?'this':''" @click="category=0">全部</li> <li :class="category==item.id?'this':''" v-for="item in category_list" @click="category=item.id">{{item.name}}</li> </ul> <div class="ordering"> <ul> <li class="title">筛 选: </li> <li class="default this">默认</li> <li class="hot this">人气</li> <li class="price this">价格</li> </ul> <p class="condition-result">共21个课程</p> </div> </div> <!-- 课程列表 --> <div class="course-list"> <div class="course-item" v-for="course in course_list"> <div class="course-image"> <img :src="course.course_img" alt=""> </div> <div class="course-info"> <h3><router-link to="/course/detail/1">{{course.name}}</router-link> <span><img src="/static/image/avatar1.svg" alt="">{{course.students}}人已加入学习</span></h3> <p class="teather-info">{{course.teacher.role_name}} {{course.teacher.name}} {{course.teacher.signature}} {{course.teacher.title}} <span>共{{course.lessons}}课时/{{course.lessons==course.pub_lessons?'更新完成':'已更新'+course.pub_lessons+'课时'}}</span></p> <ul class="lesson-list"> <li v-for="lesson,key in course.recomment_lessons"><span class="lesson-title">0{{key+1}} | 第{{lesson.id}}节:{{lesson.name}}</span> <span class="free" v-if="lesson.free_trail">免费</span></li> </ul> <div class="pay-box"> <span class="discount-type">限时免费</span> <span class="discount-price">¥0.00元</span> <span class="original-price">原价:{{course.price}}元</span> <span class="buy-now">立即购买</span> </div> </div> </div> </div> </div> <Footer></Footer> </div> </template> <script> import Header from "./common/Header" import Footer from "./common/Footer" export default { name: "Course", data(){ return{ category: 0, // 当前点击的课程分类ID,0表示默认值,全部 category_list: [], // 课程分类列表 course_list: [ { teacher: {}, } ], } }, created(){ this.get_course_category(); this.get_course(); }, methods:{ get_course_category(){ // 获取课程分类 this.$axios.get(`${this.$settings.Host}/courses/category/`).then(response=>{ this.category_list = response.data; }).catch(error=>{ this.$message.error("无法获取课程分类信息!"); }) }, get_course(){ // 获取课程信息 this.$axios.get(`${this.$settings.Host}/courses/`).then(response=>{ this.course_list = response.data; }).catch(error=>{ this.$message.error("无法获取课程信息!"); }) } }, components:{ Header, Footer, } } </script> <style scoped> .course{ background: #f6f6f6; } .course .main{ width: 1100px; margin: 35px auto 0; } .course .condition{ margin-bottom: 35px; padding: 25px 30px 25px 20px; background: #fff; border-radius: 4px; box-shadow: 0 2px 4px 0 #f0f0f0; } .course .cate-list{ border-bottom: 1px solid #333; border-bottom-color: rgba(51,51,51,.05); padding-bottom: 18px; margin-bottom: 17px; } .course .cate-list::after{ content:""; display: block; clear: both; } .course .cate-list li{ float: left; font-size: 16px; padding: 6px 15px; line-height: 16px; margin-left: 14px; position: relative; transition: all .3s ease; cursor: pointer; color: #4a4a4a; border: 1px solid transparent; /* transparent 透明 */ } .course .cate-list .title{ color: #888; margin-left: 0; letter-spacing: .36px; padding: 0; line-height: 28px; } .course .cate-list .this{ color: #ffc210; border: 1px solid #ffc210!important; border-radius: 30px; } .course .ordering::after{ content:""; display: block; clear: both; } .course .ordering ul{ float: left; } .course .ordering ul::after{ content:""; display: block; clear: both; } .course .ordering .condition-result{ float: right; font-size: 14px; color: #9b9b9b; line-height: 28px; } .course .ordering ul li{ float: left; padding: 6px 15px; line-height: 16px; margin-left: 14px; position: relative; transition: all .3s ease; cursor: pointer; color: #4a4a4a; } .course .ordering .title{ font-size: 16px; color: #888; letter-spacing: .36px; margin-left: 0; padding:0; line-height: 28px; } .course .ordering .this{ color: #ffc210; } .course .ordering .price{ position: relative; } .course .ordering .price::before, .course .ordering .price::after{ cursor: pointer; content:""; display: block; width: 0px; height: 0px; border: 5px solid transparent; position: absolute; right: 0; } .course .ordering .price::before{ border-bottom: 5px solid #aaa; margin-bottom: 2px; top: 2px; } .course .ordering .price::after{ border-top: 5px solid #aaa; bottom: 2px; } .course .course-item:hover{ box-shadow: 4px 6px 16px rgba(0,0,0,.5); } .course .course-item{ width: 1050px; background: #fff; padding: 20px 30px 20px 20px; margin-bottom: 35px; border-radius: 2px; cursor: pointer; box-shadow: 2px 3px 16px rgba(0,0,0,.1); /* css3.0 过渡动画 hover 事件操作 */ transition: all .2s ease; } .course .course-item::after{ content:""; display: block; clear: both; } /* 顶级元素 父级元素 当前元素{} */ .course .course-item .course-image{ float: left; width: 423px; height: 210px; margin-right: 30px; } .course .course-item .course-image img{ width: 100%; } .course .course-item .course-info{ float: left; width: 596px; } .course-item .course-info h3 { font-size: 26px; color: #333; font-weight: normal; margin-bottom: 8px; } .course-item .course-info h3 span{ font-size: 14px; color: #9b9b9b; float: right; margin-top: 14px; } .course-item .course-info h3 span img{ width: 11px; height: auto; margin-right: 7px; } .course-item .course-info .teather-info{ font-size: 14px; color: #9b9b9b; margin-bottom: 14px; padding-bottom: 14px; border-bottom: 1px solid #333; border-bottom-color: rgba(51,51,51,.05); } .course-item .course-info .teather-info span{ float: right; } .course-item .lesson-list::after{ content:""; display: block; clear: both; } .course-item .lesson-list li { float: left; width: 44%; font-size: 14px; color: #666; padding-left: 22px; /* background: url("路径") 是否平铺 x轴位置 y轴位置 */ background: url("/static/image/play-icon-gray.svg") no-repeat left 4px; margin-bottom: 15px; } .course-item .lesson-list li .lesson-title{ /* 以下3句,文本内容过多,会自动隐藏,并显示省略符号 */ text-overflow: ellipsis; overflow: hidden; white-space: nowrap; display:inline-block; max-width: 200px; } .course-item .lesson-list li:hover{ background-image: url("/static/image/play-icon-yellow.svg"); color: #ffc210; } .course-item .lesson-list li .free{ width: 34px; height: 20px; color: #fd7b4d; vertical-align: super; margin-left: 10px; border: 1px solid #fd7b4d; border-radius: 2px; text-align: center; font-size: 13px; white-space: nowrap; } .course-item .lesson-list li:hover .free{ color: #ffc210; border-color: #ffc210; } .course-item .pay-box::after{ content:""; display: block; clear: both; } .course-item .pay-box .discount-type{ padding: 6px 10px; font-size: 16px; color: #fff; text-align: center; margin-right: 8px; background: #fa6240; border: 1px solid #fa6240; border-radius: 10px 0 10px 0; float: left; } .course-item .pay-box .discount-price{ font-size: 24px; color: #fa6240; float: left; } .course-item .pay-box .original-price{ text-decoration: line-through; font-size: 14px; color: #9b9b9b; margin-left: 10px; float: left; margin-top: 10px; } .course-item .pay-box .buy-now{ width: 120px; height: 38px; background: transparent; color: #fa6240; font-size: 16px; border: 1px solid #fd7b4d; border-radius: 3px; transition: all .2s ease-in-out; float: right; text-align: center; line-height: 38px; } .course-item .pay-box .buy-now:hover{ color: #fff; background: #ffc210; border: 1px solid #ffc210; } </style>
在当前项目中安装 字段过滤排序
pip install django-filter
在settings/dev.py配置文件中增加过滤后端的设置:
INSTALLED_APPS = [ ... 'django_filters', # 需要注册应用, ]
在视图中设置允许过滤的字段名和引入过滤字段核心类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from rest_framework.generics import ListAPIView from .models import Course from django_filters.rest_framework import DjangoFilterBackend from rest_framework.filters import OrderingFilter class CourseListAPIView(ListAPIView): """课程列表""" queryset = Course.objects.filter(is_show=True, is_delete=False).order_by("orders", "-id") serializer_class = CourseModelSerializer filter_backends = [DjangoFilterBackend,OrderingFilter ] filter_fields = ('course_category',) ordering_fields =('id','students','price')
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<template> <div class="course"> <Header></Header> <div class="main"> <!-- 筛选条件 --> <div class="condition"> <ul class="cate-list"> <li class="title">课程分类:</li> <li :class="filters.category==0?'this':''" @click="filters.category=0">全部</li> <li :class="filters.category==item.id?'this':''" v-for="item in category_list" @click="filters.category=item.id">{{item.name}}</li> </ul> <div class="ordering"> <ul> <li class="title">筛 选: </li> <li class="default this">默认</li> <li class="hot this">人气</li> <li class="price this">价格</li> </ul> <p class="condition-result">共21个课程</p> </div> </div> <!-- 课程列表 --> <div class="course-list"> <div class="course-item" v-for="course in course_list"> <div class="course-image"> <img :src="course.course_img" alt=""> </div> <div class="course-info"> <h3><router-link to="/course/detail/1">{{course.name}}</router-link> <span><img src="/static/image/avatar1.svg" alt="">{{course.students}}人已加入学习</span></h3> <p class="teather-info">{{course.teacher.role_name}} {{course.teacher.name}} {{course.teacher.signature}} {{course.teacher.title}} <span>共{{course.lessons}}课时/{{course.lessons==course.pub_lessons?'更新完成':'已更新'+course.pub_lessons+'课时'}}</span></p> <ul class="lesson-list"> <li v-for="lesson,key in course.recomment_lessons"><span class="lesson-title">0{{key+1}} | 第{{lesson.id}}节:{{lesson.name}}</span> <span class="free" v-if="lesson.free_trail">免费</span></li> </ul> <div class="pay-box"> <span class="discount-type">限时免费</span> <span class="discount-price">¥0.00元</span> <span class="original-price">原价:{{course.price}}元</span> <span class="buy-now">立即购买</span> </div> </div> </div> </div> </div> <Footer></Footer> </div> </template> <script> import Header from "./common/Header" import Footer from "./common/Footer" export default { name: "Course", data(){ return{ filters:{ category: 0, // 当前点击的课程分类ID,0表示默认值,全部 }, category_list: [], // 课程分类列表 course_list: [ { teacher: {}, } ], } }, created(){ this.get_course_category(); this.get_course(); }, watch:{ // 每次分类ID进行l修改,都要重新获取一次课程别彪信息 "filters.category":function () { this.get_course(); }, }, methods:{ get_course_category(){ // 获取课程分类 this.$axios.get(`${this.$settings.Host}/courses/category/`).then(response=>{ this.category_list = response.data; }).catch(error=>{ this.$message.error("无法获取课程分类信息!"); }) }, get_course(){ // 获取课程列表 let filters = { }; // 判断课程分类ID不是0,则需要指定分类到后端查询对应分类的数据,拼接参数 if(this.filters.category != 0){ filters.course_category = this.filters.category; } // 获取课程信息 this.$axios.get(`${this.$settings.Host}/courses/`,{ params:filters }).then(response=>{ this.course_list = response.data; }).catch(error=>{ this.$message.error("无法获取课程信息!"); }) } }, components:{ Header, Footer, } } </script> <style scoped> .course{ background: #f6f6f6; } .course .main{ width: 1100px; margin: 35px auto 0; } .course .condition{ margin-bottom: 35px; padding: 25px 30px 25px 20px; background: #fff; border-radius: 4px; box-shadow: 0 2px 4px 0 #f0f0f0; } .course .cate-list{ border-bottom: 1px solid #333; border-bottom-color: rgba(51,51,51,.05); padding-bottom: 18px; margin-bottom: 17px; } .course .cate-list::after{ content:""; display: block; clear: both; } .course .cate-list li{ float: left; font-size: 16px; padding: 6px 15px; line-height: 16px; margin-left: 14px; position: relative; transition: all .3s ease; cursor: pointer; color: #4a4a4a; border: 1px solid transparent; /* transparent 透明 */ } .course .cate-list .title{ color: #888; margin-left: 0; letter-spacing: .36px; padding: 0; line-height: 28px; } .course .cate-list .this{ color: #ffc210; border: 1px solid #ffc210!important; border-radius: 30px; } .course .ordering::after{ content:""; display: block; clear: both; } .course .ordering ul{ float: left; } .course .ordering ul::after{ content:""; display: block; clear: both; } .course .ordering .condition-result{ float: right; font-size: 14px; color: #9b9b9b; line-height: 28px; } .course .ordering ul li{ float: left; padding: 6px 15px; line-height: 16px; margin-left: 14px; position: relative; transition: all .3s ease; cursor: pointer; color: #4a4a4a; } .course .ordering .title{ font-size: 16px; color: #888; letter-spacing: .36px; margin-left: 0; padding:0; line-height: 28px; } .course .ordering .this{ color: #ffc210; } .course .ordering .price{ position: relative; } .course .ordering .price::before, .course .ordering .price::after{ cursor: pointer; content:""; display: block; width: 0px; height: 0px; border: 5px solid transparent; position: absolute; right: 0; } .course .ordering .price::before{ border-bottom: 5px solid #aaa; margin-bottom: 2px; top: 2px; } .course .ordering .price::after{ border-top: 5px solid #aaa; bottom: 2px; } .course .course-item:hover{ box-shadow: 4px 6px 16px rgba(0,0,0,.5); } .course .course-item{ width: 1050px; background: #fff; padding: 20px 30px 20px 20px; margin-bottom: 35px; border-radius: 2px; cursor: pointer; box-shadow: 2px 3px 16px rgba(0,0,0,.1); /* css3.0 过渡动画 hover 事件操作 */ transition: all .2s ease; } .course .course-item::after{ content:""; display: block; clear: both; } /* 顶级元素 父级元素 当前元素{} */ .course .course-item .course-image{ float: left; width: 423px; height: 210px; margin-right: 30px; } .course .course-item .course-image img{ width: 100%; } .course .course-item .course-info{ float: left; width: 596px; } .course-item .course-info h3 { font-size: 26px; color: #333; font-weight: normal; margin-bottom: 8px; } .course-item .course-info h3 span{ font-size: 14px; color: #9b9b9b; float: right; margin-top: 14px; } .course-item .course-info h3 span img{ width: 11px; height: auto; margin-right: 7px; } .course-item .course-info .teather-info{ font-size: 14px; color: #9b9b9b; margin-bottom: 14px; padding-bottom: 14px; border-bottom: 1px solid #333; border-bottom-color: rgba(51,51,51,.05); } .course-item .course-info .teather-info span{ float: right; } .course-item .lesson-list::after{ content:""; display: block; clear: both; } .course-item .lesson-list li { float: left; width: 44%; font-size: 14px; color: #666; padding-left: 22px; /* background: url("路径") 是否平铺 x轴位置 y轴位置 */ background: url("/static/image/play-icon-gray.svg") no-repeat left 4px; margin-bottom: 15px; } .course-item .lesson-list li .lesson-title{ /* 以下3句,文本内容过多,会自动隐藏,并显示省略符号 */ text-overflow: ellipsis; overflow: hidden; white-space: nowrap; display:inline-block; max-width: 200px; } .course-item .lesson-list li:hover{ background-image: url("/static/image/play-icon-yellow.svg"); color: #ffc210; } .course-item .lesson-list li .free{ width: 34px; height: 20px; color: #fd7b4d; vertical-align: super; margin-left: 10px; border: 1px solid #fd7b4d; border-radius: 2px; text-align: center; font-size: 13px; white-space: nowrap; } .course-item .lesson-list li:hover .free{ color: #ffc210; border-color: #ffc210; } .course-item .pay-box::after{ content:""; display: block; clear: both; } .course-item .pay-box .discount-type{ padding: 6px 10px; font-size: 16px; color: #fff; text-align: center; margin-right: 8px; background: #fa6240; border: 1px solid #fa6240; border-radius: 10px 0 10px 0; float: left; } .course-item .pay-box .discount-price{ font-size: 24px; color: #fa6240; float: left; } .course-item .pay-box .original-price{ text-decoration: line-through; font-size: 14px; color: #9b9b9b; margin-left: 10px; float: left; margin-top: 10px; } .course-item .pay-box .buy-now{ width: 120px; height: 38px; background: transparent; color: #fa6240; font-size: 16px; border: 1px solid #fd7b4d; border-radius: 3px; transition: all .2s ease-in-out; float: right; text-align: center; line-height: 38px; } .course-item .pay-box .buy-now:hover{ color: #fff; background: #ffc210; border: 1px solid #ffc210; } </style>
前段实现点击不同的排序方式的高粱显示效果
course.vu
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<template> <div class="course"> <Header></Header> <div class="main"> <!-- 筛选条件 --> <div class="condition"> <ul class="cate-list"> <li class="title">课程分类:</li> <li :class="filters.category==0?'this':''" @click="filters.category=0">全部</li> <li :class="filters.category==item.id?'this':''" v-for="item in category_list" @click="filters.category=item.id">{{item.name}}</li> </ul> <div class="ordering"> <ul> <li class="title">筛 选: </li> <li class="default" :class="filters.ordering=='id'?'this asc': (filters.ordering=='-id'?'this desc':'')" @click="select_ordering('id')">默认</li> <li class="hot" :class="filters.ordering=='students'?'this asc': (filters.ordering=='-students'?'this desc':'')" @click="select_ordering('students')">人气</li> <li class="price" :class="filters.ordering=='price'?'this asc': (filters.ordering=='-price'?'this desc':'')" @click="select_ordering('price')">价格</li> </ul> <p class="condition-result">共21个课程</p> </div> </div> <!-- 课程列表 --> <div class="course-list"> <div class="course-item" v-for="course in course_list"> <div class="course-image"> <img :src="course.course_img" alt=""> </div> <div class="course-info"> <h3><router-link to="/course/detail/1">{{course.name}}</router-link> <span><img src="/static/image/avatar1.svg" alt="">{{course.students}}人已加入学习</span></h3> <p class="teather-info">{{course.teacher.role_name}} {{course.teacher.name}} {{course.teacher.signature}} {{course.teacher.title}} <span>共{{course.lessons}}课时/{{course.lessons==course.pub_lessons?'更新完成':'已更新'+course.pub_lessons+'课时'}}</span></p> <ul class="lesson-list"> <li v-for="lesson,key in course.recomment_lessons"><span class="lesson-title">0{{key+1}} | 第{{lesson.id}}节:{{lesson.name}}</span> <span class="free" v-if="lesson.free_trail">免费</span></li> </ul> <div class="pay-box"> <span class="discount-type">限时免费</span> <span class="discount-price">¥0.00元</span> <span class="original-price">原价:{{course.price}}元</span> <span class="buy-now">立即购买</span> </div> </div> </div> </div> </div> <Footer></Footer> </div> </template> <script> import Header from "./common/Header" import Footer from "./common/Footer" export default { name: "Course", data(){ return{ filters:{ category: 0, // 当前点击的课程分类ID,0表示默认值,全部 ordering: "id", // id默认,students人气, price价格,如果值的左边有-减号,则表示倒叙,否则是正序 }, category_list: [], // 课程分类列表 course_list: [ { teacher: {}, } ], } }, created(){ this.get_course_category(); this.get_course(); }, watch:{ // 每次分类ID进行l修改,都要重新获取一次课程别彪信息 "filters.category":function () { this.get_course(); }, "filters.ordering": function(){ this.get_course(); }, }, methods:{ get_course_category(){ // 获取课程分类 this.$axios.get(`${this.$settings.Host}/courses/category/`).then(response=>{ this.category_list = response.data; }).catch(error=>{ this.$message.error("无法获取课程分类信息!"); }) }, get_course(){ // 获取课程列表 let filters = { "ordering": this.filters.ordering, }; // 判断课程分类ID不是0,则需要指定分类到后端查询对应分类的数据,拼接参数 if(this.filters.category != 0){ filters.course_category = this.filters.category; } // 获取课程信息 this.$axios.get(`${this.$settings.Host}/courses/`,{ params:filters }).then(response=>{ this.course_list = response.data; }).catch(error=>{ this.$message.error("无法获取课程信息!"); }) }, select_ordering(ordering){ // 判断切换不同的排序方式 if(ordering=="id"){ // 点击了默认 if(this.filters.ordering=="id"){ this.filters.ordering="-id"; }else{ this.filters.ordering="id"; } }else if(ordering=="students"){ // 点击了人气 if(this.filters.ordering=="students"){ this.filters.ordering="-students"; }else{ this.filters.ordering="students"; } }else if(ordering=="price"){ // 点击了价格 if(this.filters.ordering=="price"){ this.filters.ordering="-price"; }else{ this.filters.ordering="price"; } } }, }, components:{ Header, Footer, } } </script> <style scoped> .course{ background: #f6f6f6; } .course .main{ width: 1100px; margin: 35px auto 0; } .course .condition{ margin-bottom: 35px; padding: 25px 30px 25px 20px; background: #fff; border-radius: 4px; box-shadow: 0 2px 4px 0 #f0f0f0; } .course .cate-list{ border-bottom: 1px solid #333; border-bottom-color: rgba(51,51,51,.05); padding-bottom: 18px; margin-bottom: 17px; } .course .cate-list::after{ content:""; display: block; clear: both; } .course .cate-list li{ float: left; font-size: 16px; padding: 6px 15px; line-height: 16px; margin-left: 14px; position: relative; transition: all .3s ease; cursor: pointer; color: #4a4a4a; border: 1px solid transparent; /* transparent 透明 */ } .course .cate-list .title{ color: #888; margin-left: 0; letter-spacing: .36px; padding: 0; line-height: 28px; } .course .cate-list .this{ color: #ffc210; border: 1px solid #ffc210!important; border-radius: 30px; } .course .ordering::after{ content:""; display: block; clear: both; } .course .ordering ul{ float: left; } .course .ordering ul::after{ content:""; display: block; clear: both; } .course .ordering .condition-result{ float: right; font-size: 14px; color: #9b9b9b; line-height: 28px; } .course .ordering ul li{ float: left; padding: 6px 15px; line-height: 16px; margin-left: 14px; position: relative; transition: all .3s ease; cursor: pointer; color: #4a4a4a; } .course .ordering .title{ font-size: 16px; color: #888; letter-spacing: .36px; margin-left: 0; padding:0; line-height: 28px; } .course .ordering .this{ color: #ffc210; } .course .ordering .price{ position: relative; } .course .ordering .this::before, .course .ordering .this::after{ cursor: pointer; content:""; display: block; width: 0px; height: 0px; border: 5px solid transparent; position: absolute; right: 0; } .course .ordering .this::before{ border-bottom: 5px solid #aaa; margin-bottom: 2px; top: 2px; } .course .ordering .this::after{ border-top: 5px solid #aaa; bottom: 2px; } .course .ordering .desc::after{ border-top: 5px solid #ffc210; } .course .ordering .asc::before{ border-bottom: 5px solid #ffc210; } .course .course-item:hover{ box-shadow: 4px 6px 16px rgba(0,0,0,.5); } .course .course-item{ width: 1050px; background: #fff; padding: 20px 30px 20px 20px; margin-bottom: 35px; border-radius: 2px; cursor: pointer; box-shadow: 2px 3px 16px rgba(0,0,0,.1); /* css3.0 过渡动画 hover 事件操作 */ transition: all .2s ease; } .course .course-item::after{ content:""; display: block; clear: both; } /* 顶级元素 父级元素 当前元素{} */ .course .course-item .course-image{ float: left; width: 423px; height: 210px; margin-right: 30px; } .course .course-item .course-image img{ width: 100%; } .course .course-item .course-info{ float: left; width: 596px; } .course-item .course-info h3 { font-size: 26px; color: #333; font-weight: normal; margin-bottom: 8px; } .course-item .course-info h3 span{ font-size: 14px; color: #9b9b9b; float: right; margin-top: 14px; } .course-item .course-info h3 span img{ width: 11px; height: auto; margin-right: 7px; } .course-item .course-info .teather-info{ font-size: 14px; color: #9b9b9b; margin-bottom: 14px; padding-bottom: 14px; border-bottom: 1px solid #333; border-bottom-color: rgba(51,51,51,.05); } .course-item .course-info .teather-info span{ float: right; } .course-item .lesson-list::after{ content:""; display: block; clear: both; } .course-item .lesson-list li { float: left; width: 44%; font-size: 14px; color: #666; padding-left: 22px; /* background: url("路径") 是否平铺 x轴位置 y轴位置 */ background: url("/static/image/play-icon-gray.svg") no-repeat left 4px; margin-bottom: 15px; } .course-item .lesson-list li .lesson-title{ /* 以下3句,文本内容过多,会自动隐藏,并显示省略符号 */ text-overflow: ellipsis; overflow: hidden; white-space: nowrap; display:inline-block; max-width: 200px; } .course-item .lesson-list li:hover{ background-image: url("/static/image/play-icon-yellow.svg"); color: #ffc210; } .course-item .lesson-list li .free{ width: 34px; height: 20px; color: #fd7b4d; vertical-align: super; margin-left: 10px; border: 1px solid #fd7b4d; border-radius: 2px; text-align: center; font-size: 13px; white-space: nowrap; } .course-item .lesson-list li:hover .free{ color: #ffc210; border-color: #ffc210; } .course-item .pay-box::after{ content:""; display: block; clear: both; } .course-item .pay-box .discount-type{ padding: 6px 10px; font-size: 16px; color: #fff; text-align: center; margin-right: 8px; background: #fa6240; border: 1px solid #fa6240; border-radius: 10px 0 10px 0; float: left; } .course-item .pay-box .discount-price{ font-size: 24px; color: #fa6240; float: left; } .course-item .pay-box .original-price{ text-decoration: line-through; font-size: 14px; color: #9b9b9b; margin-left: 10px; float: left; margin-top: 10px; } .course-item .pay-box .buy-now{ width: 120px; height: 38px; background: transparent; color: #fa6240; font-size: 16px; border: 1px solid #fd7b4d; border-radius: 3px; transition: all .2s ease-in-out; float: right; text-align: center; line-height: 38px; } .course-item .pay-box .buy-now:hover{ color: #fff; background: #ffc210; border: 1px solid #ffc210; } </style>
课程列表接口实现分页显示数据(分页)
在当前子应用courses下创建一个分页器的文件paginations.py,代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from rest_framework.pagination import PageNumberPagination class CoursePageNumberPagination(PageNumberPagination): """课程列表数据的分页器""" page_query_param = "page" # 页码参数 page_size_query_param = 'size' # 单页数据量 page_size = 5 # 默认的单页数据量,就是每一页显示5个课程信息 max_page_size = 20 # 允许客户端设置的单页数据量
视图中加载声明的分页器,代码:
courses/views.py
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from .models import Course from .serializers import CourseModelSerializer from django_filters.rest_framework import DjangoFilterBackend from rest_framework.filters import OrderingFilter from .paginations import CoursePageNumberPagination class CourseListAPIView(ListAPIView): """课程列表""" queryset = Course.objects.filter(is_show=True, is_delete=False).order_by("orders", "-id") serializer_class = CourseModelSerializer pagination_class = CoursePageNumberPagination filter_backends = [DjangoFilterBackend, OrderingFilter] filter_fields = ['course_category'] ordering_fields = ['id', 'students', 'price']
客户端请求后端发送数据
Course.vue
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<template> <div class="course"> <Header></Header> <div class="main"> <!-- 筛选条件 --> <div class="condition"> <ul class="cate-list"> <li class="title">课程分类:</li> <li :class="filters.category==0?'this':''" @click="filters.category=0">全部</li> <li :class="filters.category==item.id?'this':''" v-for="item in category_list" @click="filters.category=item.id">{{item.name}}</li> </ul> <div class="ordering"> <ul> <li class="title">筛 选: </li> <li class="default" :class="filters.ordering=='id'?'this asc': (filters.ordering=='-id'?'this desc':'')" @click="select_ordering('id')">默认</li> <li class="hot" :class="filters.ordering=='students'?'this asc': (filters.ordering=='-students'?'this desc':'')" @click="select_ordering('students')">人气</li> <li class="price" :class="filters.ordering=='price'?'this asc': (filters.ordering=='-price'?'this desc':'')" @click="select_ordering('price')">价格</li> </ul> <p class="condition-result">共{{course_total}}个课程</p> </div> </div> <!-- 课程列表 --> <div class="course-list"> <div class="course-item" v-for="course in course_list"> <div class="course-image"> <img :src="course.course_img" alt=""> </div> <div class="course-info"> <h3><router-link to="/course/detail/1">{{course.name}}</router-link> <span><img src="/static/image/avatar1.svg" alt="">{{course.students}}人已加入学习</span></h3> <p class="teather-info">{{course.teacher.role_name}} {{course.teacher.name}} {{course.teacher.signature}} {{course.teacher.title}} <span>共{{course.lessons}}课时/{{course.lessons==course.pub_lessons?'更新完成':'已更新'+course.pub_lessons+'课时'}}</span></p> <ul class="lesson-list"> <li v-for="lesson,key in course.recomment_lessons"><span class="lesson-title">0{{key+1}} | 第{{lesson.id}}节:{{lesson.name}}</span> <span class="free" v-if="lesson.free_trail">免费</span></li> </ul> <div class="pay-box"> <span class="discount-type">限时免费</span> <span class="discount-price">¥0.00元</span> <span class="original-price">原价:{{course.price}}元</span> <span class="buy-now">立即购买</span> </div> </div> </div> </div> <el-pagination v-if="course_total>1" background :page-size="filters.size" :page-sizes="[2, 5, 10, 20]" layout="sizes, prev, pager, next" @size-change="handleSizeChange" :current-page="filters.page" @current-change="handleCurrentChange" :total="course_total"> </el-pagination> </div> <Footer></Footer> </div> </template> <script> import Header from "./common/Header" import Footer from "./common/Footer" export default { name: "Course", data(){ return{ filters:{ page: 1, size: 5, category: 0, // 当前点击的课程分类ID,0表示默认值,全部 ordering: "id", // id默认,students人气, price价格,如果值的左边有-减号,则表示倒叙,否则是正序 }, category_list: [], // 课程分类列表 course_total: 0, // 当前课程的总数量 course_list: [ { teacher: {}, } ], } }, created(){ this.get_course_category(); this.get_course(); }, watch:{ // 每次分类ID进行了修改,都要重新获取一次课程列表信息 "filters.category": function(){ this.filters.page = 1; this.get_course(); }, "filters.ordering": function(){ this.get_course(); }, "filters.page": function(){ this.get_course(); }, "filters.size": function(){ this.filters.page = 1; // this.get_course(); }, }, methods:{ get_course_category(){ // 获取课程分类 this.$axios.get(`${this.$settings.Host}/courses/category/`).then(response=>{ this.category_list = response.data; }).catch(error=>{ this.$message.error("无法获取课程分类信息!"); }) }, get_course(){ // 获取课程列表 let filters = { "ordering": this.filters.ordering, }; // 判断课程分类ID不是0,则需要指定分类到后端查询对应分类的数据,拼接参数 if(this.filters.category != 0){ filters.course_category = this.filters.category; } filters.page = this.filters.page; filters.size = this.filters.size; // 获取课程信息 this.$axios.get(`${this.$settings.Host}/courses/`,{ params: filters }).then(response=>{ this.course_list = response.data.results; // 课程列表 this.course_total = response.data.count; // 课程总数 }).catch(error=>{ this.$message.error("无法获取课程信息!"); }) }, select_ordering(ordering){ // 判断切换不同的排序方式 if(ordering=="id"){ // 点击了默认 if(this.filters.ordering=="id"){ this.filters.ordering="-id"; }else{ this.filters.ordering="id"; } }else if(ordering=="students"){ // 点击了人气 if(this.filters.ordering=="students"){ this.filters.ordering="-students"; }else{ this.filters.ordering="students"; } }else if(ordering=="price"){ // 点击了价格 if(this.filters.ordering=="price"){ this.filters.ordering="-price"; }else{ this.filters.ordering="price"; } } }, handleCurrentChange(page){ // 切换页码 this.filters.page = page; }, handleSizeChange(size){ // 切换单页显示数据量 this.filters.size = size; } }, components:{ Header, Footer, } } </script> <style scoped> .course{ background: #f6f6f6; } .course .main{ width: 1100px; margin: 35px auto 0; } .course .condition{ margin-bottom: 35px; padding: 25px 30px 25px 20px; background: #fff; border-radius: 4px; box-shadow: 0 2px 4px 0 #f0f0f0; } .course .cate-list{ border-bottom: 1px solid #333; border-bottom-color: rgba(51,51,51,.05); padding-bottom: 18px; margin-bottom: 17px; } .course .cate-list::after{ content:""; display: block; clear: both; } .course .cate-list li{ float: left; font-size: 16px; padding: 6px 15px; line-height: 16px; margin-left: 14px; position: relative; transition: all .3s ease; cursor: pointer; color: #4a4a4a; border: 1px solid transparent; /* transparent 透明 */ } .course .cate-list .title{ color: #888; margin-left: 0; letter-spacing: .36px; padding: 0; line-height: 28px; } .course .cate-list .this{ color: #ffc210; border: 1px solid #ffc210!important; border-radius: 30px; } .course .ordering::after{ content:""; display: block; clear: both; } .course .ordering ul{ float: left; } .course .ordering ul::after{ content:""; display: block; clear: both; } .course .ordering .condition-result{ float: right; font-size: 14px; color: #9b9b9b; line-height: 28px; } .course .ordering ul li{ float: left; padding: 6px 15px; line-height: 16px; margin-left: 14px; position: relative; transition: all .3s ease; cursor: pointer; color: #4a4a4a; } .course .ordering .title{ font-size: 16px; color: #888; letter-spacing: .36px; margin-left: 0; padding:0; line-height: 28px; } .course .ordering .this{ color: #ffc210; } .course .ordering .price{ position: relative; } .course .ordering .this::before, .course .ordering .this::after{ cursor: pointer; content:""; display: block; width: 0px; height: 0px; border: 5px solid transparent; position: absolute; right: 0; } .course .ordering .this::before{ border-bottom: 5px solid #aaa; margin-bottom: 2px; top: 2px; } .course .ordering .this::after{ border-top: 5px solid #aaa; bottom: 2px; } .course .ordering .desc::after{ border-top: 5px solid #ffc210; } .course .ordering .asc::before{ border-bottom: 5px solid #ffc210; } .course .course-item:hover{ box-shadow: 4px 6px 16px rgba(0,0,0,.5); } .course .course-item{ width: 1050px; background: #fff; padding: 20px 30px 20px 20px; margin-bottom: 35px; border-radius: 2px; cursor: pointer; box-shadow: 2px 3px 16px rgba(0,0,0,.1); /* css3.0 过渡动画 hover 事件操作 */ transition: all .2s ease; } .course .course-item::after{ content:""; display: block; clear: both; } /* 顶级元素 父级元素 当前元素{} */ .course .course-item .course-image{ float: left; width: 423px; height: 210px; margin-right: 30px; } .course .course-item .course-image img{ width: 100%; } .course .course-item .course-info{ float: left; width: 596px; } .course-item .course-info h3 { font-size: 26px; color: #333; font-weight: normal; margin-bottom: 8px; } .course-item .course-info h3 span{ font-size: 14px; color: #9b9b9b; float: right; margin-top: 14px; } .course-item .course-info h3 span img{ width: 11px; height: auto; margin-right: 7px; } .course-item .course-info .teather-info{ font-size: 14px; color: #9b9b9b; margin-bottom: 14px; padding-bottom: 14px; border-bottom: 1px solid #333; border-bottom-color: rgba(51,51,51,.05); } .course-item .course-info .teather-info span{ float: right; } .course-item .lesson-list::after{ content:""; display: block; clear: both; } .course-item .lesson-list li { float: left; width: 44%; font-size: 14px; color: #666; padding-left: 22px; /* background: url("路径") 是否平铺 x轴位置 y轴位置 */ background: url("/static/image/play-icon-gray.svg") no-repeat left 4px; margin-bottom: 15px; } .course-item .lesson-list li .lesson-title{ /* 以下3句,文本内容过多,会自动隐藏,并显示省略符号 */ text-overflow: ellipsis; overflow: hidden; white-space: nowrap; display:inline-block; max-width: 200px; } .course-item .lesson-list li:hover{ background-image: url("/static/image/play-icon-yellow.svg"); color: #ffc210; } .course-item .lesson-list li .free{ width: 34px; height: 20px; color: #fd7b4d; vertical-align: super; margin-left: 10px; border: 1px solid #fd7b4d; border-radius: 2px; text-align: center; font-size: 13px; white-space: nowrap; } .course-item .lesson-list li:hover .free{ color: #ffc210; border-color: #ffc210; } .course-item .pay-box::after{ content:""; display: block; clear: both; } .course-item .pay-box .discount-type{ padding: 6px 10px; font-size: 16px; color: #fff; text-align: center; margin-right: 8px; background: #fa6240; border: 1px solid #fa6240; border-radius: 10px 0 10px 0; float: left; } .course-item .pay-box .discount-price{ font-size: 24px; color: #fa6240; float: left; } .course-item .pay-box .original-price{ text-decoration: line-through; font-size: 14px; color: #9b9b9b; margin-left: 10px; float: left; margin-top: 10px; } .course-item .pay-box .buy-now{ width: 120px; height: 38px; background: transparent; color: #fa6240; font-size: 16px; border: 1px solid #fd7b4d; border-radius: 3px; transition: all .2s ease-in-out; float: right; text-align: center; line-height: 38px; } .course-item .pay-boxthis .buy-now:hover{ color: #fff; background: #ffc210; border: 1px solid #ffc210; } </style>
修改分页样式中的字体大小和居中,static/reset.css,代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
.el-pagination{ text-align: center; margin-top: 18px; margin-bottom: 28px; }