IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Python知识库 -> 后台品牌管理功能实现 -> 正文阅读

[Python知识库]后台品牌管理功能实现

新建子应用

在现在的后台项目里再创建一个goods子应用
再settings.py文件里注册子应用
路由分发,新建urls.py文件
配置序列化器,创建serializers.py

创建模型类

在子应用下的models.py文件中创建

from django.db import models
# Create your models here.
class Brand(models.Model):
    first_name=models.CharField('品牌首字母',max_length=10,default=None)
    name=models.CharField('品牌名称',max_length=20)
    # 用来存储图片地址
    logo=models.CharField('品牌logo',max_length=200)
    def __str__(self):
        return self.name
    class Meta:
        db_table='brand'
        verbose_name_plural='品牌'

生成迁移文件进行迁移

往里添加几条数据
例如:
在这里插入图片描述
需要配置静态文件
在根目录创建static文件夹
在项目根目录中的settings.py里进行配置

STATIC_URL = '/static/'
STATICFILES_DIRS=(       #注意,逗号不能忘记加
    os.path.join(BASE_DIR,'static'),
)

编写序列化器

在子应用下创建serializers.py文件中创建

from rest_framework import serializers
from .models import *
#定义品牌的序列化器
class BrandSer(serializers.ModelSerializer):
    #                         输入允许为空
    logo=serializers.CharField(allow_null=True,allow_blank=True)
    class Meta:
        model=Brand
        fields='__all__'
        # 只能序列化输出  只读
        read_only_fields=['id']

编写视图类

from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from rest_framework.views import APIView
from rest_framework.response import Response
from p6_306 import settings
from .models import *
from .serializers import *
import os
# Create your views here.
#分页器类
from rest_framework.pagination import PageNumberPagination
class MyPagination(PageNumberPagination):
    page_size = 3
    max_page_size = 5
    page_query_param = 'page'
    page_size_query_param = 'pageSize'
#品牌的视图集
class BrandViewSet(ModelViewSet):
    queryset = Brand.objects.all()
    serializer_class = BrandSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'
    pagination_class = MyPagination

#上传logo的视图
class UploadLogoAPIView(APIView):
    def post(self,request):
        #1.获取前端的数据
        file=request.data.get('file')
        #2.拼接一下路径
        static_path='static/images/logos'
        file_path=os.path.join(settings.BASE_DIR,static_path)
        #最终文件名
        file_name=os.path.join(file_path,file.name)
        # 3.保存图片的字节流
        with open(file_name,'wb')as f:
            f.write(file.file.read())
        return Response({
            'code':200,
            'msg':'图片上传成功',
            'static_path':static_path
        })

配置路由

from django.urls import path
from rest_framework import routers
from .views import *
urlpatterns = [
 #上传logo
    path('upload/logo/',UploadLogoAPIView.as_view())
]
#品牌的路由
router=routers.SimpleRouter()
router.register('brands',BrandViewSet,'brands')
urlpatterns+=router.urls

前端

找到对应的vue组件进行配置
展示全部品牌信息
组件例如:Brands.vue

<script>
import BreadCrumb from '@/components/widget/BreadCrumb'
// 添加的子组件
import Addbrands from '@/components/widget/AddBrands'   
// 展示 删除 修改 的子组件
import BrandsTable from '@/components/widget/BrandsTable'  
export default {
  name: 'Brands',
  data () {
    return {
      page:1,
      total:0,
      pagesize:2,
      aBrandsList:[]
    }
  },
  components:{
    BreadCrumb,
    Addbrands,
    BrandsTable
  },
  mounted(){
    this.fnGetData(1);
  },
  methods:{
    fnGetData(num){  // 接收全部品牌信息
      this.axios.get('/v1/goods/brands/',{
        params:{
          page:num,
          pageSize:this.pageSize
        },
        headers:{
          Authorization:'JWT '+localStorage.token
        },
        responseType:'json'
      }).then((result) => {
        console.log('加载所有品牌的响应',result)
        if (result.status==200){
          this.aBrandsList=result.data.results
          this.total=result.data.count
        }else{
          this.$message({
            type:'error',
            message:'加载品牌错误'
          })
        }
      }).catch((err) => {
        console.log('加载失败的响应',err)
      });
    },
    // 加载对应页面的数据
    fnGetPage(page){
      this.page=page
      this.fnGetData(page)
    },
  }
}
</script>

展示删除修改的vue组件
在这里插入图片描述

<script>
import cons from '../constant';
// import cons from '@/components/constant';
let token = localStorage.token;
export default {
  name: 'OptionsTable',
  // 接收父组件传递的值
  props:['brands'],
   data () { 
    return {
      host:'http://127.0.0.1:8000',
      pop_show:false,
      group_type_list:[],
      category_list:[],
      BrandsForm:{
        name:'',
        first_name:'',
        logo:''
      },
      fileList:[],
      rulesBrandsForm:{}
    }
  },
  methods:{
    handleSuccess(res,files){
      console.log('上传成功的响应',res)
      this.BrandsForm.logo='/'+res.static_path+'/'+files.name
    },
    // 点击编辑触发的方法
  	fnPopShow(id){
  		this.pop_show = true;
      this.edit_id = id;
      this.axios.get('/v1/goods/brands/'+this.edit_id+'/', {
            headers: {
              'Authorization': 'JWT ' + token
            },
            responseType: 'json',
        })
        .then(res=>{
           this.BrandsForm.name = res.data.name;
           this.BrandsForm.logo = res.data.logo;
           this.BrandsForm.first_name = res.data.first_name;
        }).catch(err=>{
           console.log(err.response);
      });
  	},
    // 修改点击提交触发的方法
  	submitForm(){
  		this.axios.put('/v1/goods/brands/'+this.edit_id+'/', this.BrandsForm, {
            headers: {
              'Authorization': 'JWT ' + token
            },
            responseType: 'json'           
        }).then(res=>{
          this.$message({
            type: 'success',
            message: '品牌修改成功!'
          }); 
        	this.pop_show = false;           
          this.resetForm('ChannelsForm');
          this.$emit('fnResetTable');
        }).catch(err=>{
        	console.log(err.response);
        })
  	},
    // 删除品牌
  	fnDelBrands(id){
        this.edit_id = id;
        this.$confirm('此操作将删除该品牌, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.axios.delete('/v1/goods/brands/'+this.edit_id+'/',{
              headers: {
                'Authorization': 'JWT ' + token
              },
              responseType:'json'           
          }).then(res=>{
            console.log('删除品牌的响应',res)
            if (res.status==204){
              this.$message({
              type: 'success',
              message: '删除品牌成功!'
            });
            this.$emit('fnResetTable');
            }else{
              this.$message({
                type: 'error',
                message: '删除品牌失败!'
              });
            }
            
          }).catch(err=>{
            if(err.response.status==404){
               this.$message({
                  type:'info',
                  message:'图片未找到!'
                });
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });  		
  	},
    resetForm(formName){
      this.$refs[formName].resetFields();
    }
  },
  mounted(){
    this.fnGetChannelType();
    this.fnGetCategories();
  }
}
</script>

添加的组件

<script>
// import cons from '@/components/constant';
let token = localStorage.token;
export default {
  name: 'AddChannels',
  data () { 
    return {
      daka:false,
      host:'http://127.0.0.1:8000',
      pop_show:false,
      group_type_list:[],
      category_list:[],
      BrandsForm:{
        name:'',
        first_name:'',
        logo:''
      },
      fileList:[],
      rulesBrandsForm:{}
    }
  },
  methods:{
    handleSuccess(res,files){
      console.log('上传成功的响应',res)
      this.BrandsForm.logo='/'+res.static_path+'/'+files.name
      this.daka=true
    },
    // 点击提交触发的方法
    submitForm(){
        this.axios.post('/v1/goods/brands/',this.BrandsForm,{
          headers:{
            Authorization:'JWT '+token
          },
          responseType:'json'
        }).then((result) => {
          if (result.status==201){
            this.$message({
              type:'success',
              message:'添加品牌成功'
            })
          this.pop_show=false
          this.resetForm('BrandsForm')
          this.$emit('fnResetTable')
          }else{
            this.$message({
              type:'error',
              message:'添加品牌失败'
            })
          }
        }).catch((err) => {
          console.log('添加品牌错误',err)
        });
    },
    fnGetChannelType(){},
    fnGetCategories(){},
    resetForm(formName){
      this.$refs[formName].resetFields();
      this.daka=false
    }
  },
  mounted(){
    this.fnGetChannelType();
    this.fnGetCategories();
  }
}
</script>
  Python知识库 最新文章
Python中String模块
【Python】 14-CVS文件操作
python的panda库读写文件
使用Nordic的nrf52840实现蓝牙DFU过程
【Python学习记录】numpy数组用法整理
Python学习笔记
python字符串和列表
python如何从txt文件中解析出有效的数据
Python编程从入门到实践自学/3.1-3.2
python变量
上一篇文章      下一篇文章      查看所有文章
加:2022-07-04 22:49:56  更:2022-07-04 22:52:53 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/18 12:06:14-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码