luffy项目:基于vue与drf前后台分离项目(2)
user模块User表
创建user模块
前提:在 luffy 虚拟环境下 1.终端从项目根目录进入apps目录 >: cd luffyapi & cd apps 2.创建app >: python ../../manage.py startapp user
from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): mobile = models.CharField(max_length=11, unique=True) icon = models.ImageField(upload_to='icon', default='icon/default.png') class Meta: db_table = 'luffy_user' verbose_name = '用户表' verbose_name_plural = verbose_name def __str__(self): return self.username
INSTALLED_APPS = [ # ... 'user', ] # 自定义User表 AUTH_USER_MODEL = 'user.User'
配置media
dev.py
MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
media目录配置
""" ├── luffyapi └── luffyapi/ └── media/ └── icon └── default.png """
from django.contrib import admin from django.urls import path, re_path, include from django.views.static import serve from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('user/', include('user.urls')), re_path('^media/(?P<path>.*)', serve, {'document_root': settings.MEDIA_ROOT}) ]
from django.urls import path, re_path urlpatterns = [ ]
前台搭建
vue化境
1.傻瓜式安装node: 官网下载:https://nodejs.org/zh-cn/ 2.安装cnpm: >: npm install -g cnpm --registry=https://registry.npm.taobao.org 3.安装vue最新脚手架: >: cnpm install -g @vue/cli 注:如果2、3步报错,清除缓存后重新走2、3步 >: npm cache clean --force
创建项目
""" 前提:在目标目录新建luffy文件夹 >: cd 建立的luffy文件夹
>: vue create luffycity """
重构项目目录
""" ├── luffycity ├── public/ # 项目共有资源 ├── favicon.ico # 站点图标 └── index.html # 主页 ├── src/ # 项目主应用,开发时的代码保存 ├── assets/ # 前台静态资源总目录 ├── css/ # 自定义css样式 └── global.css # 自定义全局样式 ├── js/ # 自定义js样式 └── settings.js # 自定义配置文件 └── img/ # 前台图片资源 ├── components/ # 小组件目录 ├── views/ # 页面组件目录 ├── App.vue # 根路由 ├── main.js # 入口脚本文件 ├── router └── index.js # 路由脚本文件 store └── index.js # 仓库脚本文件 ├── vue.config.js # 项目配置文件 └── *.* # 其他配置文件 """
文件修订:目录中飞配置文件的多余文件可以移除:
app.vue
<template> <div id="app"> <router-view/> </div> </template>
import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../views/Home.vue' Vue.use(VueRouter); const routes = [ { path: '/', name: 'home', component: Home }, ]; const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }); export default router
Home.vue
<template> <div class="home"> </div> </template> <script> export default { name: 'home', components: { }, } </script>
全局配置:全局样式、配置文件
global.css
/* 声明全局样式和项目的初始化样式 */ body, h1, h2, h3, h4, 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; /* 合并边框 */ }
settings.js 默认的url连接跳转,前后台交互,发送AjAx数据请求。
export default { base_url: 'http://127.0.0.1:8000' }
main.js
// 配置全局样式 import '@/assets/css/global.css' // 配置全局自定义设置 import settings from '@/assets/js/settings' Vue.prototype.$settings = settings; // 在所有需要与后台交互的组件中:this.$settings.base_url + '再拼接具体后台路由'
项目重构,添加
luffy前台配置
axios前台交互
安装:前端项目目录下的终端输入:
>: cnpm install axios
配置:main.js
import axios from 'axios' Vue.prototype.$axios = axios;
cookies操作
安装:前端项目目录下的终端输入:
>: cnpm install vue-cookies
配置:main.js
import cookies from 'vue-cookies' Vue.prototype.$cookies = cookies;
element-ui页面组件框架
安装:前端项目目录下的终端
>: cnpm install element-ui
配置:main.js
import ElementUI from 'element-ui'; import 'element-ui/lib/theme-chalk/index.css'; Vue.use(ElementUI); // bootstrap+jq配置:cnpm install jquery、cnpm install bootstrap@3 import 'bootstrap' import 'bootstrap/dist/css/bootstrap.min.css'
bootstrap 页面组件框架
安装:
>: cnpm install jquery
>: cnpm install bootstrap@3
配置JQuery:vue.config.js 创建的固定文件名,位于主目录下面。
const webpack = require("webpack"); module.exports = { configureWebpack: { plugins: [ new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery", "window.$": "jquery", Popper: ["popper.js", "default"] }) ] } };
配置bootstrap:main.js
import 'bootstrap'
import 'bootstrap/dist/css/bootstrap.min.css'
前端主页
图片准备,将提供的资料图片复制到项目的img文件下
页头组件:components/Header.vue
<template> <div class="header-box"> <div class="header"> <div class="content"> <div class="logo full-left"> <router-link to="/"><img @click="jump('/')" src="@/assets/img/logo.svg" alt=""></router-link> </div> <ul class="nav full-left"> <li><span @click="jump('/course')" :class="this_nav=='/course'?'this':''">免费课</span></li> <li><span @click="jump('/light-course')" :class="this_nav=='/light-course'?'this':''">轻课</span></li> <li><span>学位课</span></li> <li><span>题库</span></li> <li><span>老男孩教育</span></li> </ul> <div class="login-bar full-right"> <div class="shop-cart full-left"> <img src="@/assets/img/cart.svg" alt=""> <span><router-link to="/cart">购物车</router-link></span> </div> <div class="login-box full-left"> <span>登录</span> | <span>注册</span> </div> </div> </div> </div> </div> </template> <script> export default { name: "Header", data() { return { this_nav: "", } }, created() { this.this_nav = localStorage.this_nav; }, methods: { jump(location) { localStorage.this_nav = location; // vue-router除了提供router-link标签跳转页面以外,还提供了js跳转的方式 this.$router.push(location); } } } </script> <style scoped> .header-box { height: 80px; } .header { width: 100%; height: 80px; box-shadow: 0 0.5px 0.5px 0 #c9c9c9; position: fixed; top: 0; left: 0; right: 0; margin: auto; z-index: 99; background: #fff; } .header .content { max-width: 1200px; width: 100%; margin: 0 auto; } .header .content .logo { height: 80px; line-height: 80px; margin-right: 50px; cursor: pointer; } .header .content .logo img { vertical-align: middle; } .header .nav li { float: left; height: 80px; line-height: 80px; margin-right: 30px; font-size: 16px; color: #4a4a4a; cursor: pointer; } .header .nav li span { padding-bottom: 16px; padding-left: 5px; padding-right: 5px; } .header .nav li span a { display: inline-block; } .header .nav li .this { color: #4a4a4a; border-bottom: 4px solid #ffc210; } .header .nav li:hover span { color: #000; } .header .login-bar { height: 80px; } .header .login-bar .shop-cart { margin-right: 20px; border-radius: 17px; background: #f7f7f7; cursor: pointer; font-size: 14px; height: 28px; width: 88px; margin-top: 30px; line-height: 32px; text-align: center; } .header .login-bar .shop-cart:hover { background: #f0f0f0; } .header .login-bar .shop-cart img { width: 15px; margin-right: 4px; margin-left: 6px; } .header .login-bar .shop-cart span { margin-right: 6px; } .header .login-bar .login-box { margin-top: 33px; } .header .login-bar .login-box span { color: #4a4a4a; cursor: pointer; } .header .login-bar .login-box span:hover { color: #000000; } .full-left { float: left !important; } .full-right { float: right !important; } .el-carousel__arrow { width: 120px; height: 120px; } .el-checkbox__input.is-checked .el-checkbox__inner, .el-checkbox__input.is-indeterminate .el-checkbox__inner { background: #ffc210; border-color: #ffc210; border: none; } .el-checkbox__inner:hover { border-color: #9b9b9b; } .el-checkbox__inner { width: 16px; height: 16px; border: 1px solid #9b9b9b; border-radius: 0; } .el-checkbox__inner::after { height: 9px; width: 5px; } </style>
轮播图组件:components/Banner.vue
<template> <el-carousel height="520px" :interval="3000" arrow="always"> <el-carousel-item> <img src="@/assets/img/banner1.png" alt=""> </el-carousel-item> <el-carousel-item> <img src="@/assets/img/banner2.png" alt=""> </el-carousel-item> <el-carousel-item> <img src="@/assets/img/banner3.png" alt=""> </el-carousel-item> </el-carousel> </template> <script> export default { name: "Banner", } </script> <style scoped> .el-carousel__item h3 { color: #475669; font-size: 18px; opacity: 0.75; line-height: 300px; margin: 0; } .el-carousel__item:nth-child(2n) { background-color: #99a9bf; } .el-carousel__item:nth-child(2n+1) { background-color: #d3dce6; } .el-carousel__item img { text-align: center; height: 520px; margin: 0 auto; display: block; } </style>
页脚组件:components/Footer.vue
<template> <div class="footer"> <ul> <li>关于我们</li> <li>联系我们</li> <li>商务合作</li> <li>帮助中心</li> <li>意见反馈</li> <li>新手指南</li> </ul> <p>Copyright © luffycity.com版权所有 | 京ICP备17072161号-1</p> </div> </template> <script> export default { name: "Footer" } </script> <style scoped> .footer { width: 100%; height: 128px; background: #25292e; color: #fff; } .footer ul { margin: 0 auto 16px; padding-top: 38px; width: 810px; } .footer ul li { float: left; width: 112px; margin: 0 10px; text-align: center; font-size: 14px; } .footer ul::after { content: ""; display: block; clear: both; } .footer p { text-align: center; font-size: 12px; } </style>
主页组件:views/Home.vue
<template> <div class="home"> <Header /> <Banner /> <Footer /> </div> </template> <script> import Header from '@/components/Header' import Banner from '@/components/Banner' import Footer from '@/components/Footer' export default { name: 'home', components: { Header, Banner, Footer }, } </script>
后台主页模块设计
创建home模块,创建应用appd到指定的文件apps目录下。
前提:在 luffy 虚拟环境下 1.终端从项目根目录进入apps目录 >: cd luffyapi & cd apps 2.创建app >: python ../../manage.py startapp home
路由分发
主路由:Luffyapi/urls.py
from django.urls import path, re_path, include urlpatterns = [ # ... path('user/', include('home.urls')), # ... ]
子路由:home/urls.py
from django.urls import path, re_path urlpatterns = [ ]
Banner数据表models的设计
utils/models.py
from django.db import models class BaseModel(models.Model): orders = models.IntegerField(verbose_name='显示顺序') is_show = models.BooleanField(verbose_name="是否上架", default=False) is_delete = models.BooleanField(verbose_name="逻辑删除", default=False) class Meta: abstract = True
home/models.py
from django.db import models from utils.model import BaseModel class Banner(BaseModel): image = models.ImageField(upload_to='banner', verbose_name='轮播图', null=True, blank=True) name = models.CharField(max_length=150, verbose_name='轮播图名称') note = models.CharField(max_length=150, verbose_name='备注信息') link = models.CharField(max_length=150, verbose_name='轮播图广告地址') class Meta: db_table = 'luffy_banner' verbose_name = '轮播图' verbose_name_plural = verbose_name def __str__(self): return self.name
数据库的迁移:在大luffyapi路径下的终端输入完整的执行命令
>: python manage.py makemigrations
>: python manage.py migrate
注册home模块:dev.py >> settings
INSTALLED_APPS = [ # ... 'rest_framework', 'home', ]
设计Banner数据接口
home/serializers.py
from rest_framework.serializers import ModelSerializer from . import models class BannerModelSerializer(ModelSerializer): class Meta: model = models.Banner fields = ('name', 'note', 'image', 'link')
home/views.py
from rest_framework.generics import ListAPIView from utils.response import APIResponse from . import models, serializers class BannerListAPIView(ListAPIView): queryset = models.Banner.objects.filter(is_delete=False, is_show=True).order_by('-orders') serializer_class = serializers.BannerModelSerializer
home/urls.py
from django.urls import path, re_path from . import views urlpatterns = [ path('banners/', views.BannerListAPIView.as_view()) ]
接口
http://api.luffy.cn:8000/home/banner/
前后台分离跨域交互
后台处理跨域
安装插件
>: pip install django-cors-headers
插件参考地址:https://github.com/ottoyiu/django-cors-headers/
项目配置:dev.py
# 注册app INSTALLED_APPS = [ ... 'corsheaders' ] # 添加中间件 MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware' ] # 允许跨域源 CORS_ORIGIN_ALLOW_ALL = True
前台请求Banner数据
修订Banner.vue
<template> <el-carousel height="520px" :interval="3000" arrow="always"> <!-- 渲染后台数据 --> <el-carousel-item v-for="banner in banner_list" :key="banner.name"> <a :href="banner.link"> <img :src="banner.image" alt="" :title="banner.note"> </a> </el-carousel-item> </el-carousel> </template> <script> export default { name: "Banner", data() { return { banner_list: [] } }, created() { // 请求后台数据 this.$axios({ url: this.$settings.base_url + '/home/banners/', method: 'get', }).then(response => { // window.console.log(response.data); this.banner_list = response.data; }).catch(errors => { window.console.log(errors) }) } } </script> <style scoped> .el-carousel__item h3 { color: #475669; font-size: 18px; opacity: 0.75; line-height: 300px; margin: 0; } .el-carousel__item:nth-child(2n) { background-color: #99a9bf; } .el-carousel__item:nth-child(2n+1) { background-color: #d3dce6; } .el-carousel__item img { text-align: center; height: 520px; margin: 0 auto; display: block; } </style>
xadmin后台管理
和django原生的admin功能是类似的,只是有一些渲染的效果页面。
安装:luffy虚拟环境下
# >: pip install https://codeload.github.com/sshwsfc/xadmin/zip/django2
官网获取:
注册app:dev.py,目的是替换掉原来自带的admin
INSTALLED_APPS = [ # ... # xamin主体模块 'xadmin', # 渲染表格模块 'crispy_forms', # 为模型通过版本控制,可以回滚数据 'reversion', ]
xadmin:需要自己的数据库模型类,完成数据迁移
>>python manage.py makemigrations
>>python manage.py migrate
设置主路由替换掉admin:主urls.py
# xadmin的依赖 import xadmin xadmin.autodiscover() # xversion模块自动注册需要版本控制的 Model from xadmin.plugins import xversion xversion.register_models() urlpatterns = [ # ... path(r'xadmin/', xadmin.site.urls), ]
创建超级用户:大luffyapi路径下的终端
# 在项目根目录下的终端 python manage.py createsuperuser # 账号密码设置:admin | admin123
完成xadmin全局配置:新建home/adminx.py
# home/adminx.py # xadmin全局配置 import xadmin from xadmin import views class GlobalSettings(object): """xadmin的全局配置""" site_title = "路飞学城" # 设置站点标题 site_footer = "路飞学城有限公司" # 设置站点的页脚 menu_style = "accordion" # 设置菜单折叠 xadmin.site.register(views.CommAdminView, GlobalSettings)
在adminx.py中注册model:home/adminx.px
from . import models # 注册 xadmin.site.register(models.Banner)
修改app:home的名字:xadmin页面上的显示效果
# home/__init__.py default_app_config = "home.apps.HomeConfig" # home/apps.py from django.apps import AppConfig class HomeConfig(AppConfig): name = 'home' verbose_name = '我的首页'
修改后,xadmin后天管理的界面
本文来自博客园,作者:游走De提莫,转载请注明原文链接:https://www.cnblogs.com/Gaimo/p/11746013.html