轮播图功能
安装依赖模块
图片处理模块
pip install pillow
上传文件相关配置
由于我们需要在后台上传我们的轮播图图片,所以我们需要在django中配置一下上传文件的相关配置,有了它之后,就不需要我们自己写上传文件,保存文件的操作了,看配置 dev.py
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, "uploads")
MEDIA_URL = "/media/"
总路由urls.py 在django项目中转换上传文件的Url地址,总路由urls.py新增代码:
from django.contrib import admin
from django.urls import path, re_path, include
from django.views.static import serve
from django.conf import settings
import xadmin
xadmin.autodiscover()
from xadmin.plugins import xversion
xversion.register_models()
urlpatterns = [
path(r'xadmin/', xadmin.site.urls),
re_path(r'media/(?P<path>.*)', serve, {"document_root": settings.MEDIA_ROOT}),
]
注册home子应用
因为当前功能是drf的第一个功能,所以我们先创建一个子应用home,创建在lyapi/apps目录下
cd lyapi/apps/
python manage.py startapp home
注册home子应用,因为子应用的位置发生了改变,所以为了原来子应用的注册写法,所以新增一个导包路径: dev.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
import sys
sys.path.insert(0,os.path.join(BASE_DIR,"apps"))
...
INSTALLED_APPS = [
...
'rest_framework',
...
'home',
]
创建轮播图的model模型
apps/home/models.py
from django.db import models
class Banner(models.Model):
"""轮播广告图模型"""
title = models.CharField(max_length=500, verbose_name="广告标题")
link = models.CharField(max_length=500, verbose_name="广告链接")
image_url = models.ImageField(upload_to="banner", null=True, blank=True, max_length=255, verbose_name="广告图片")
remark = models.TextField(verbose_name="备注信息")
is_show = models.BooleanField(default=False, verbose_name="是否显示")
orders = models.IntegerField(default=1, verbose_name="排序")
is_deleted = models.BooleanField(default=False, verbose_name="是否删除")
class Meta:
db_table = "ly_banner"
verbose_name = "轮播广告"
verbose_name_plural = verbose_name
def __str__(self):
return self.title
执行数据库迁移指令
python manage.py makemigrations
python manage.py migrate
创建Banner的序列化器
apps/home/serializers.py
from rest_framework import serializers
from . import models
class BannerModelSeiralizer(serializers.ModelSerializer):
class Meta:
model = models.Banner
fields = ['id', 'title', 'link', 'image_url']
创建Banner的视图类
apps/home/views.py
from rest_framework.generics import ListAPIView
from . import models
from .serializer import BannerModelSeiralizer
from lyapi.settings import contains
class BannerView(ListAPIView):
queryset = models.Banner.objects.filter(is_show=True, is_deleted=False).order_by('orders')[0:contains.BANNER_LENGTH]
serializer_class = BannerModelSeiralizer
在settings配置文件夹中创建一个constants.py配置文件,将来里面存放我们所有的一些常量信息配置,比如上面的轮播图数据切片长度 settings/constant.py
BANNER_LENGTH = 3
配置Banner的路由
总路由utils/urls.py
from django.urls import path, re_path, include
from django.views.static import serve
from django.conf import settings
import xadmin
xadmin.autodiscover()
from xadmin.plugins import xversion
xversion.register_models()
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'media/(?P<path>.*)', serve, {"document_root": settings.MEDIA_ROOT}),
path(r'home/', include('home.urls')),
]
应用中的路由apps/home/urls.py
from django.urls import path, re_path
from django.conf import settings
from . import views
urlpatterns = [
path(r'banner/', views.BannerView.as_view()),
]
配置Xadmin
配置文件注册Xadmin应用
settings/dev.py
INSTALLED_APPS = [
...
'home',
'users',
'xadmin',
'crispy_forms',
'reversion',
]
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'
xadmin有建立自己的数据库模型类,需要进行数据库迁移
python manage.py makemigrations
python manage.py migrate
在总路由中添加xadmin的路由信息
from django.urls import path, re_path, include
from django.views.static import serve
from django.conf import settings
import xadmin
xadmin.autodiscover()
from xadmin.plugins import xversion
xversion.register_models()
urlpatterns = [
path(r'xadmin/', xadmin.site.urls),
]
给Xadmin配置基本的站点信息
home/adminx.py
import xadmin
from xadmin import views
class BaseSetting(object):
"""xadmin的基本配置"""
enable_themes = True
use_bootswatch = True
xadmin.site.register(views.BaseAdminView, BaseSetting)
class GlobalSettings(object):
"""xadmin的全局配置"""
site_title = "莽夫学城"
site_footer = "莽夫学城有限公司"
menu_style = "accordion"
xadmin.site.register(views.CommAdminView, GlobalSettings)
创建超级管理员
python manage.py createsuperuser
注册轮播图模型到xadmin中
apps/home/adminx.py 在当前子应用中创建adminx.py,添加如下代码
class BannerXadmin(object):
list_display = ['id', 'title', 'link', 'image_url', 'is_show']
xadmin.site.register(models.Banner, BannerXadmin)
修改后端Xadmin中子应用名称
apps/home/apps.py
from django.apps import AppConfig
class HomeConfig(AppConfig):
name = 'home'
verbose_name = '我的首页'
apps/home/__ init__.py
default_app_config = "home.apps.HomeConfig"
给轮播图添加测试数据
经过上面的操作,我们就完成了轮播图的API接口,接下来,可以考虑提交一个代码版本.
git add .
git commit -m "服务端实现轮播图的API接口"
git push origin master
web端代码获取数据
src/components/Home.vue
<template>
<div class="home">
<Header></Header>
<Banner></Banner>
<Footer></Footer>
</div>
</template>
<script>
import Header from '@/components/common/Header'
import Banner from '@/components/common/Banner'
import Footer from '@/components/common/Footer'
export default {
name: "Home",
components: {
Header,
Banner,
Footer,
}
}
</script>
<style scoped>
</style>
src/components/common/Banner.vue
<template>
<el-carousel indicator-position="outside" height="400px">
<el-carousel-item v-for="(value,index) in banner_list" :key="index">
<a :href="value.link" target="_blank">
<img :src="value.image_url" alt="" style="width: 100%;height: 400px">
</a>
</el-carousel-item>
</el-carousel>
</template>
<script>
export default {
name: "Banner",
data() {
return {
banner_list: [],
}
},
created() {
this.$axios.get(`${this.$settings.host}/home/banner/`)
.then((res) => {
this.banner_list = res.data;
})
.catch((error) => {
})
},
}
</script>
<style scoped>
</style>
导航栏的实现
前端导航栏子组件Header的代码
lyweb/src/components/common/Header.vue
<template>
<div class="total-header">
<div class="header">
<el-container>
<el-header height="80px" class="header-cont">
<el-row>
<el-col class="logo" :span="3">
<a href="/">
<img src="@/assets/head-logo.svg" alt="">
</a>
</el-col>
<el-col class="nav" :span="10">
<el-row>
<el-col :span="4" v-for="(top_nav, index) in nav_top_list" :key="top_nav.id">
<router-link :to="top_nav.link" v-if="!top_nav.is_site">{{ top_nav.title }}</router-link>
<a :href="top_nav.link" target="_blank" v-else>{{ top_nav.title }}</a>
</el-col>
</el-row>
</el-col>
<el-col :span="11" class="header-right-box">
<div class="search">
<input type="text" id="Input" placeholder="请输入想搜索的课程" style="" @blur="inputShowHandler"
ref="Input" v-show="!s_status">
<ul @click="ulShowHandler" v-show="s_status" class="search-ul">
<span>Python</span>
<span>Linux</span>
</ul>
<p>
<img class="icon" src="@/assets/sousuo1.png" alt="" v-show="s_status">
<img class="icon" src="@/assets/sousuo2.png" alt="" v-show="!s_status">
<img class="new" src="@/assets/new.png" alt="">
</p>
</div>
<div class="register" v-show="!token">
<router-link to="/login">
<button class="signin">登录</button>
</router-link>
|
<a target="_blank" href="https://www.luffycity.com/signup">
<router-link to="/register">
<button class="signup">注册</button>
</router-link>
</a>
</div>
<div class="shop-car" v-show="token">
<router-link to="/cart">
<b>6</b>
<img src="@/assets/shopcart.png" alt="">
<span>购物车 </span>
</router-link>
</div>
<div class="nav-right-box" v-show="token">
<div class="nav-right">
<router-link to="/myclass">
<div class="nav-study">我的教室</div>
</router-link>
<div class="nav-img" @mouseover="personInfoList" @mouseout="personInfoOut">
<img src="@/assets/touxiang.png" alt="" style="border: 1px solid rgb(243, 243, 243);">
<ul class="home-my-account" v-show="list_status" @mouseover="personInfoList">
<li>
我的账户
<img src="" alt="@/assets/back.svg">
</li>
<li>
我的订单
<img src="@/assets/back.svg" alt="">
</li>
<li>
贝里小卖铺
<img src="@/assets/back.svg" alt="">
</li>
<li>
我的优惠券
<img src="@/assets/back.svg" alt="">
</li>
<li>
<span>
我的消息
<b>(26)</b>
</span>
<img src="" alt="">
</li>
<li>
退出
<img src="" alt="">
</li>
</ul>
</div>
</div>
</div>
</el-col>
</el-row>
</el-header>
</el-container>
</div>
</div>
</template>
<script>
export default {
name: "Header",
data() {
return {
token: false,
s_status: true,
list_status: false,
nav_top_list: [],
where: 0,
}
},
methods: {
checklogin() {
if (localStorage.token) {
this.token = localStorage.token
this.where = 1;
} else if (sessionStorage.token) {
this.token = sessionStorage.token
this.where = 0;
} else {
return false;
}
this.$axios.post(`${this.$settings.host}/users/verify_token/`, {
token: this.token,
})
.then((res) => {
if (this.where === 0) {
sessionStorage.token = res.data.token;
} else {
localStorage.token = res.data.token;
}
})
.catch((error) => {
this.$confirm('请重新登录', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
this.$router.push('/login');
}).catch(() => {
this.token = false;
})
})
},
ulShowHandler() {
this.s_status = false;
this.$nextTick(() => {
this.$refs.Input.focus();
})
},
inputShowHandler() {
this.s_status = true;
},
personInfoList() {
this.list_status = true;
},
personInfoOut() {
this.list_status = false;
},
get_nav_data() {
this.$axios.get(`${this.$settings.host}/home/nav/top`)
.then((res) => {
this.nav_top_list = res.data;
})
.catch((error) => {
})
},
},
created() {
this.get_nav_data();
this.checklogin();
}
}
</script>
<style scoped>
.header-cont .nav .active {
color: #f5a623;
font-weight: 500;
border-bottom: 2px solid #f5a623;
}
.total-header {
min-width: 1200px;
z-index: 100;
box-shadow: 0 4px 8px 0 hsla(0, 0%, 59%, .1);
}
.header {
width: 1200px;
margin: 0 auto;
}
.header .el-header {
padding: 0;
}
.logo {
height: 80px;
display: flex;
align-items: center;
}
.nav .el-row .el-col {
height: 80px;
line-height: 80px;
text-align: center;
}
.nav a {
font-size: 15px;
font-weight: 400;
cursor: pointer;
color: #4a4a4a;
text-decoration: none;
}
.nav .el-row .el-col a:hover {
border-bottom: 2px solid #f5a623
}
.header-cont {
position: relative;
}
.search input {
width: 185px;
height: 26px;
font-size: 14px;
color: #4a4a4a;
border: none;
border-bottom: 1px solid #ffc210;
outline: none;
}
.search ul {
width: 185px;
height: 26px;
display: flex;
align-items: center;
padding: 0;
padding-bottom: 3px;
border-bottom: 1px solid hsla(0, 0%, 59%, .25);
cursor: text;
margin: 0;
font-family: Helvetica Neue, Helvetica, Microsoft YaHei, Arial, sans-serif;
}
.search .search-ul, .search #Input {
padding-top: 10px;
}
.search ul span {
color: #545c63;
font-size: 12px;
padding: 3px 12px;
background: #eeeeef;
cursor: pointer;
margin-right: 3px;
border-radius: 11px;
}
.hide {
display: none;
}
.search {
height: auto;
display: flex;
}
.search p {
position: relative;
margin-right: 20px;
margin-left: 4px;
}
.search p .icon {
width: 16px;
height: 16px;
cursor: pointer;
}
.search p .new {
width: 18px;
height: 10px;
position: absolute;
left: 15px;
top: 0;
}
.register {
height: 36px;
display: flex;
align-items: center;
line-height: 36px;
}
.register .signin, .register .signup {
font-size: 14px;
color: #5e5e5e;
white-space: nowrap;
}
.register button {
outline: none;
cursor: pointer;
border: none;
background: transparent;
}
.register a {
color: #000;
outline: none;
}
.header-right-box {
height: 100%;
display: flex;
align-items: center;
font-size: 15px;
color: #4a4a4a;
position: absolute;
right: 0;
top: 0;
}
.shop-car {
width: 99px;
height: 28px;
border-radius: 15px;
margin-right: 20px;
background: #f7f7f7;
display: flex;
align-items: center;
justify-content: center;
position: relative;
cursor: pointer;
}
.shop-car b {
position: absolute;
left: 28px;
top: -1px;
width: 18px;
height: 16px;
color: #fff;
font-size: 12px;
font-weight: 350;
display: flex;
justify-content: center;
align-items: center;
border-radius: 50%;
background: #ff0826;
overflow: hidden;
transform: scale(.8);
}
.shop-car img {
width: 20px;
height: 20px;
margin-right: 7px;
}
.nav-right-box {
position: relative;
}
.nav-right-box .nav-right {
float: right;
display: flex;
height: 100%;
line-height: 60px;
position: relative;
}
.nav-right .nav-study {
font-size: 15px;
font-weight: 300;
color: #5e5e5e;
margin-right: 20px;
cursor: pointer;
}
.nav-right .nav-study:hover {
color: #000;
}
.nav-img img {
width: 26px;
height: 26px;
border-radius: 50%;
display: inline-block;
cursor: pointer;
}
.home-my-account {
position: absolute;
right: 0;
top: 60px;
z-index: 101;
width: 190px;
height: auto;
background: #fff;
border-radius: 4px;
box-shadow: 0 4px 8px 0 #d0d0d0;
}
li {
list-style: none;
}
.home-my-account li {
height: 40px;
font-size: 14px;
font-weight: 300;
color: #5e5e5e;
padding-left: 20px;
padding-right: 20px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: space-between;
box-sizing: border-box;
}
.home-my-account li img {
cursor: pointer;
width: 5px;
height: 10px;
}
.home-my-account li span {
height: 40px;
display: flex;
align-items: center;
}
.home-my-account li span b {
font-weight: 300;
margin-top: -2px;
}
</style>
导航栏底部组件 lyweb/src/components/common/Footer.vue
<template>
<div class="footer">
<div class="footer-item">
<div class="foot-left">
<div class="foot-content">
<p>
<span>关于我们</span>
|
<span>贝里小卖铺</span>
</p>
<p>
地址:......
</p>
<p>
..........
<a class="copyright" href="http://beian.miit.gov.cn" target="_blank" >京ICP备17072161号-1</a>
</p>
<p>
<a class="report-link" target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=11010102002019&token=1ee3034d-ba3a-4cc3-89d4-89875e2dd0b1">
<img class="report-img" src="//img.alicdn.com/tfs/TB1..50QpXXXXX7XpXXXXXXXXXX-40-40.png" style="float:left" >
京公网安备 11010102002019号
</a>
</p>
</div>
</div>
<img src="@/assets/code.png" alt="" class="code">
</div>
</div>
</template>
<script>
export default {
name: "Footer"
}
</script>
<style scoped>
.footer{
display: flex;
align-items: center;
width: 100%;
height: 140px;
flex-direction: column;
overflow: hidden;
background: #191c25;
}
.footer .foot-left{
display: flex;
align-items: center;
}
.footer .foot-left .foot-content p{
margin-bottom: 10px;
font-size: 13px;
font-family: PingFangSC-Regular;
font-weight: 400;
color: #d0d0d0;
}
.footer-item{
width: 960px;
height: 100%;
justify-content: space-between;
}
.foot-left{
display: flex;
align-items: center;
float: left;
}
.foot-content a{
color: #d0d0d0;
}
.footer .foot-left .foot-content p:first-child span{
font-size: 16px;
font-weight: 400;
display: inline-block;
font-family: PingFangSC-Regular;
cursor: pointer;
}
.foot-content .report-img{
display: inline-block;
height: 20px;
margin-right: 12px;
}
.footer-item .code{
width: 74px;
height: auto;
margin-right: 100px;
float: right;
padding-top: 30px;
}
</style>
后端导航栏的实现
设计导航栏的model模型类
lyapi/lyapi/apps/home/models.py
class Nav(BaseModel):
"""导航菜单模型"""
POSITION_OPTION = (
(1, "顶部导航"),
(2, "脚部导航"),
)
title = models.CharField(max_length=500, verbose_name="导航标题")
link = models.CharField(max_length=500, verbose_name="导航链接")
position = models.IntegerField(choices=POSITION_OPTION, default=1, verbose_name="导航位置")
is_site = models.BooleanField(default=False, verbose_name="是否是站外地址")
class Meta:
db_table = 'ly_nav'
verbose_name = '导航菜单'
verbose_name_plural = verbose_name
def __str__(self):
return self.title
在Xadmin中注册导航栏模型类
from home import models
import xadmin
from xadmin import views
class NavXadmin(object):
list_display = ['id', 'title', 'link', 'position', 'is_site']
xadmin.site.register(models.Nav, NavXadmin)
数据库迁移指令
python manage.py makemigrations
python manage.py migrate
在Xadmin中添加一些导航栏数据
序列化器
lyapi/apps/home/serializer.py
from rest_framework import serializers
from . import models
class NavModelSeiralizer(serializers.ModelSerializer):
class Meta:
model = models.Nav
fields = ['id', 'title', 'link', 'is_site']
视图代码
lyapi/lyapi/apps/home/views.py
from rest_framework.generics import ListAPIView
from . import models
from .serializer import BannerModelSeiralizer, NavModelSeiralizer
from lyapi.settings import contains
class NavTopView(ListAPIView):
queryset = models.Nav.objects.filter(is_show=True, is_deleted=False, position=1).order_by('orders')[
0:contains.NAV_TOP_LENGTH]
serializer_class = NavModelSeiralizer
常量配置
lyapi/lyapi/settings/contains.py
BANNER_LENGTH = 3
NAV_TOP_LENGTH = 6
FOOTER_NAV_LENGTH = 6
路由代码
lyapi/lyapi/apps/home/urls.py
from django.urls import path, re_path
from django.conf import settings
from . import views
urlpatterns = [
path(r'banner/', views.BannerView.as_view()),
path(r'nav/top/', views.NavTopView.as_view()),
]
|