当前位置:网站首页>Realization of backstage brand management function
Realization of backstage brand management function
2022-07-27 08:28:00 【qishaoawei】
New subapplication
Create another one in the current background project goods Subapplication
Again settings.py Register the sub application in the file
Routing distribution , newly build urls.py file
Configure the serializer , establish serializers.py
Create model classes
Under sub application models.py Create in file
from django.db import models
# Create your models here.
class Brand(models.Model):
first_name=models.CharField(' Brand initials ',max_length=10,default=None)
name=models.CharField(' The brand name ',max_length=20)
# Used to store picture address
logo=models.CharField(' brand logo',max_length=200)
def __str__(self):
return self.name
class Meta:
db_table='brand'
verbose_name_plural=' brand '
Generate migration files for migration
Add a few pieces of data
for example :
Need to configure static files
Created in the root directory static Folder
In the project root directory settings.py Configuration in
STATIC_URL = '/static/'
STATICFILES_DIRS=( # Be careful , Don't forget to add a comma
os.path.join(BASE_DIR,'static'),
)
Write a serializer
Create... Under sub application serializers.py Create in file
from rest_framework import serializers
from .models import *
# Define the serializer of the brand
class BrandSer(serializers.ModelSerializer):
# The input can be null
logo=serializers.CharField(allow_null=True,allow_blank=True)
class Meta:
model=Brand
fields='__all__'
# Only output can be serialized read-only
read_only_fields=['id']
Write view classes
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.
# Pager class
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'
# View set of brands
class BrandViewSet(ModelViewSet):
queryset = Brand.objects.all()
serializer_class = BrandSer
lookup_field = 'pk'
lookup_url_kwarg = 'pk'
pagination_class = MyPagination
# Upload logo The view of
class UploadLogoAPIView(APIView):
def post(self,request):
#1. Get the front-end data
file=request.data.get('file')
#2. Splice the path
static_path='static/images/logos'
file_path=os.path.join(settings.BASE_DIR,static_path)
# The final file name
file_name=os.path.join(file_path,file.name)
# 3. Save the byte stream of the picture
with open(file_name,'wb')as f:
f.write(file.file.read())
return Response({
'code':200,
'msg':' Image upload succeeded ',
'static_path':static_path
})
Configure the routing
from django.urls import path
from rest_framework import routers
from .views import *
urlpatterns = [
# Upload logo
path('upload/logo/',UploadLogoAPIView.as_view())
]
# Brand routing
router=routers.SimpleRouter()
router.register('brands',BrandViewSet,'brands')
urlpatterns+=router.urls
front end
Find the corresponding vue Component
Show all brand information
Components such as :Brands.vue
<script> import BreadCrumb from '@/components/widget/BreadCrumb' // Added sub components import Addbrands from '@/components/widget/AddBrands' // Exhibition Delete modify The child components 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){
// Receive all brand information this.axios.get('/v1/goods/brands/',{
params:{
page:num, pageSize:this.pageSize }, headers:{
Authorization:'JWT '+localStorage.token }, responseType:'json' }).then((result) => {
console.log(' Load responses from all brands ',result) if (result.status==200){
this.aBrandsList=result.data.results this.total=result.data.count }else{
this.$message({
type:'error', message:' Loading brand error ' }) } }).catch((err) => {
console.log(' Load the failed response ',err) }); }, // Load the data of the corresponding page fnGetPage(page){
this.page=page this.fnGetData(page) }, } } </script>
Show the deleted and modified vue Components 
<script> import cons from '../constant'; // import cons from '@/components/constant'; let token = localStorage.token; export default {
name: 'OptionsTable', // Receive the value passed by the parent component 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(' Upload a successful response ',res) this.BrandsForm.logo='/'+res.static_path+'/'+files.name }, // Click Edit trigger method 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); }); }, // Modify the method triggered by clicking submit 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: ' Successful brand modification !' }); this.pop_show = false; this.resetForm('ChannelsForm'); this.$emit('fnResetTable'); }).catch(err=>{
console.log(err.response); }) }, // Delete brand fnDelBrands(id){
this.edit_id = id; this.$confirm(' This action will delete the brand , Whether or not to continue ?', ' Tips ', {
confirmButtonText: ' determine ', cancelButtonText: ' Cancel ', type: 'warning' }).then(() => {
this.axios.delete('/v1/goods/brands/'+this.edit_id+'/',{
headers: {
'Authorization': 'JWT ' + token }, responseType:'json' }).then(res=>{
console.log(' Delete brand response ',res) if (res.status==204){
this.$message({
type: 'success', message: ' Delete brand successfully !' }); this.$emit('fnResetTable'); }else{
this.$message({
type: 'error', message: ' Failed to delete brand !' }); } }).catch(err=>{
if(err.response.status==404){
this.$message({
type:'info', message:' Picture not found !' }); } }) }).catch(() => {
this.$message({
type: 'info', message: ' Delete cancelled ' }); }); }, resetForm(formName){
this.$refs[formName].resetFields(); } }, mounted(){
this.fnGetChannelType(); this.fnGetCategories(); } } </script>
Added components
<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(' Upload a successful response ',res) this.BrandsForm.logo='/'+res.static_path+'/'+files.name this.daka=true }, // Click Submit trigger method 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:' Brand added successfully ' }) this.pop_show=false this.resetForm('BrandsForm') this.$emit('fnResetTable') }else{
this.$message({
type:'error', message:' Failed to add brand ' }) } }).catch((err) => {
console.log(' Add brand error ',err) }); }, fnGetChannelType(){
}, fnGetCategories(){
}, resetForm(formName){
this.$refs[formName].resetFields(); this.daka=false } }, mounted(){
this.fnGetChannelType(); this.fnGetCategories(); } } </script>
边栏推荐
- 1176 questions of Olympiad in informatics -- who ranked K in the exam
- "Basic knowledge of PHP" implement mathematical operations in PHP
- Leetcode54. Spiral matrix
- Redis configuration file download
- Database startup report error_ user_ connect_ times &gt; 0 error
- You may need an additional loader to handle the result of these loaders.
- Eval and assert execute one sentence Trojan horse
- [target detection] yolov6 theoretical interpretation + practical test visdrone data set
- CMD command and NPM command
- redis配置文件下载
猜你喜欢

Introduction to depth first search (DFS)

redis配置文件下载

Five day travels to Beijing

带宽 与 货币

Solution to the program design of the sequence structure of one book (Chapter 1)
![[netding cup 2020 rosefinch group]nmap 1 two solutions](/img/fa/b1349cb42b5768b7510217239ba73a.png)
[netding cup 2020 rosefinch group]nmap 1 two solutions

Translation character '/b' in C #
Why do major domestic manufacturers regard cloud computing as a pastry? Do you really understand this trillion market

信息化项目风险控制与应用
![[applet] how to get wechat applet code upload key?](/img/b4/76e2f12269601c0a969a709ff8a397.png)
[applet] how to get wechat applet code upload key?
随机推荐
I can't figure out why MySQL uses b+ trees for indexing?
Breadth first search
Use of "PHP Basics" Boolean
Containerd failed to pull private database image (kubelet)
Vertical align cannot align the picture and text vertically
JS basic knowledge - daily learning summary ①
1178 questions of Olympiad in informatics -- ranking of grades
[golang] golang develops wechat official account web page authorization function
Hundreds of people participated. What are these people talking about in the opengauss open source community?
vCenter7.0管理Esxi7.0主机
Bandwidth and currency
List删除集合元素
Element display mode: block level, inline, inline block, nesting specification, display mode conversion
On Valentine's day, I drew an object with characters!
Weekly learning summary
Data extraction 2
Graph node deployment and testing
[MRCTF2020]PYWebsite 1
Use of NPM
All in one 1329 cells (breadth first search)