路飞后端配置
二次封装response
drf提供的Response对象,不能很方便的加入code和msg字段,自己封装一个Response类,以后都用我们自己封装的,方便咱们写code和msg
封装步骤:
1 在utils/common_response.py
from rest_framework.response import Response
class APIResponse(Response):
def __init__(self, code=100, msg='成功', status=None, headers=None, **kwargs):
data = {'code': code, 'msg': msg}
if kwargs:
data.update(kwargs)
super().__init__(data=data, status=status, headers=headers)
2 以后在视图类中,导入使用即可
class TestResponseView(APIView):
def get(self,request):
# return APIResponse(token='xx.xx.xx',icon='/media/icon/default.png')
# return APIResponse(msg='创建成功')
# return APIResponse(msg='用户不存在',code='101')
# return APIResponse(results=[{},{}])
return APIResponse(headers={'xx':'yy'})
封装drf五个视图扩展类
1 在utils/mixins.py
from rest_framework.mixins import ListModelMixin, DestroyModelMixin, RetrieveModelMixin, CreateModelMixin, \
UpdateModelMixin
from .common_response import APIResponseclass CommonListModelMixin(ListModelMixin):
def list(self, request, *args, **kwargs):
# Response的对象,res.data
res = super().list(request, *args, **kwargs)
return APIResponse(results=res.data) # {code:100,msg:成功,results:[{},{}]}class CommonCreateModelMixin(CreateModelMixin):
def create(self, request, *args, **kwargs):
res = super().create(request, *args, **kwargs)
return APIResponse(msg='新增成功', result=res.data) # {code:100,msg:新增成功,result:{}}class CommonDestroyModelMixin(DestroyModelMixin):
def destroy(self, request, *args, **kwargs):
super().destroy(request, *args, **kwargs)
return APIResponse(msg='删除成功') # {code:100,msg:删除成功}class CommonUpdateModelMixin(UpdateModelMixin):
def update(self, request, *args, **kwargs):
res = super().update(request, *args, **kwargs)
return APIResponse(msg='修改成功', result=res.data) # {code:100,msg:修改成功,result:{}}class CommonRetrieveModelMixin(RetrieveModelMixin):
def retrieve(self, request, *args, **kwargs):
res = super().retrieve(request, *args, **kwargs)
return APIResponse(msg='修改成功', result=res.data) # {code:100,msg:成功,result:{}}
开启media访问
# 1 新增用户---》先配置media--》以后头像都传到 media/icon 内
createsuperuser 创建用户# 2 配置文件
# media配置
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = 'media/'#3 路由
from django.views.static import serve
from django.conf import settings
path('media/<path:path>', serve, kwargs={'document_root': settings.MEDIA_ROOT}),
路飞前台项目创建和配置
创建项目
# 1 创建项目
在目标路径 vue create 项目名
# 2 删除一些不用的
-App.vue中只保留
<template>
<div id="app">
<router-view/>
</div>
</template>
# 3 HomeView.vue
<template>
<div class="home">
<h1>首页</h1>
</div>
</template>
<script>
export default {
name: 'HomeView',
}
</script>
# 4 router/index.js
const routes = [
{
path: '/',
name: 'home',
component: HomeView
},
]
记得+npm
前台全局样式和js配置
global.css
/* 声明全局样式和项目的初始化样式 */
body, h1, h2, h3, h4, h5, h6, p, table, tr, td, ul, li, a, form, input, select, option, textarea {margin: 0;padding: 0;font-size: 15px;
}a {text-decoration: none;color: #333;
}ul {list-style: none;
}table {border-collapse: collapse; /* 合并边框 */
}
main.js
// 在这导入即可--》全局样式生效
import '@/assets/css/global.css'// 在main.js中注册
import settings from "@/assets/js/settings";
Vue.prototype.$settings = settings
settings.js
export default {BASE_URL:'http://127.0.0.1:8000/'
}
# 以后再任意组件中
this.$settings.BASE_URL # 拿到基地址
axios
# 1 安装
cnpm install -S axios
# 2 在main.js中注册
import axios from "axios";
Vue.prototype.$axios = axios# 3 以后再任意组件中直接使用
this.$axios.get(this.$settings.BASE_URL+'user/user/login/')
使用elementui
# 1 安装
cnpm install element-ui -S
# 2 main.js 配置
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
操作cookie
# 安装:前端项目目录下的终端
cnpm install vue-cookies
# 配置:main.js
import cookies from 'vue-cookies'
Vue.prototype.$cookies = cookies;# 以后任意组件直接使用
this.$cookies操作即可
后台主页功能
轮播图表
# 首页
-轮播图接口
-推荐课程接口---》写到课程才能写
# 创建app,创建轮播图表
####utils/common_model.py
from django.db import models
class BaseModel(models.Model):
created_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
updated_time = models.DateTimeField(auto_now=True, verbose_name='最后更新时间')
is_delete = models.BooleanField(default=False, verbose_name='是否删除')
is_show = models.BooleanField(default=True, verbose_name='是否上架')
orders = models.IntegerField(verbose_name='优先级')class Meta:
abstract = True # 这样写了,这张表是个虚拟的,不会在数据库创建,只用来继承#####home/models.py
from utils.common_model import BaseModel
# 通过写一个BaseModel 实现,以后如果其他表中有对应字段,直接继承即可
class Banner(BaseModel):
# 排序,上传时间,是否显示,是否删除(软删除--》通过字段控制--》数据还在)
# 轮播图名字, 路径,点击跳转的页面,轮播图描述
title = models.CharField(max_length=16, unique=True, verbose_name='名称')
image = models.ImageField(upload_to='banner', verbose_name='图片')
link = models.CharField(max_length=64, verbose_name='跳转链接')
info = models.TextField(verbose_name='详情')
轮播图接口
###### 序列化类#####
from rest_framework import serializers
from .models import Banner
class BannerSerializer(serializers.ModelSerializer):
class Meta:
model = Banner
fields = ['id', 'title', 'image', 'link']#### 视图类##########
from .models import Banner
from rest_framework.viewsets import GenericViewSet
from utils.mixins import CommonListModelMixin
from .serializer import BannerSerializer
from django.conf import settings
# 查询所有轮播图
class BannerView(GenericViewSet, CommonListModelMixin):
# qs对象可以切片----》 limit 2
queryset = Banner.objects.all().filter(is_delete=False, is_show=True).order_by('orders')[:settings.BANNER_COUNT]
serializer_class = BannerSerializer
#### 路由##########
from rest_framework.routers import SimpleRouter
from .views import BannerView
router = SimpleRouter()
router.register('banner', BannerView, 'banner')
urlpatterns = [
]
urlpatterns += router.urls
自定义配置
#1 以后咱们会有自定义的配置,统一都写在
#common_settings.py中
BANNER_COUNT=3
#2 只需要在配置文件中导入
# 导入自定义配置---》统一都会给 django的的settings
from .common_settings import *#3 以后用,
from django.conf import settings
queryset = Banner.objects.all().filter(is_delete=False, is_show=True).order_by('orders')[:settings.BANNER_COUNT]