当前位置:网站首页>Management of product pictures
Management of product pictures
2022-07-27 08:29:00 【qishaoawei】
Back end
Create model classes
Foreign key binding sku Commodity list
# Model class of commodity pictures
class SKUImage(models.Model):
sku=models.ForeignKey(SKUS,on_delete=models.CASCADE,verbose_name=' goods ')
image=models.CharField(' Commodity images ',max_length=300)
def __str__(self):
return f' Name of commodity {
self.sku.name}, Commodity address {
self.image}'
class Meta:
db_table='sku_image'
verbose_name_plural=' Commodity images '
Write a serializer
#SKUImage Serializer of model class
class SKUImageSer(serializers.ModelSerializer):
sku_name=serializers.SerializerMethodField(read_only=True)
def get_sku_name(self,obj):
return obj.sku.name
class Meta:
model=SKUImage
fields='__all__'
read_only_fields=['id']
Write a serializer
Need to write a view of uploaded pictures
SKUImage The view set needs to be rewritten create Method
from rest_framework_jwt.utils import jwt_decode_handler
# View of uploaded pictures
class UploadSKUImageAPIView(APIView):
def post(self,request):
# 1. Receiving data from the front end
token=request.data.get('token')
file=request.data.get('file')
#2. verification token, Whether the certification
try:
payload=jwt_decode_handler(token)
except:
return Response({
'code':401,'msg':' Uncertified '},status=401)
#3. Handle the uploading of pictures , Save the picture
#/static/images/goods/xxx.jpg
static_path='static/image/goods'
file_path=os.path.join(settings.BASE_DIR,static_path)
# Judge file_path Whether the directory exists , Create if it does not exist
if not os.path.exists(file_path):
os.makedirs(file_path)
# Image name
image_name=os.path.join(file_path,file.name)
#4. Store image
with open(image_name,'wb')as f:
f.write(file.file.read())
# 5. Return response
return Response({
'code':200,'msg':' Upload successful ','static_path':static_path})
# skuImage View set for
class SKUImageViewSet(ModelViewSet):
queryset = SKUImage.objects.all()
serializer_class = SKUImageSer
lookup_field = 'pk'
lookup_url_kwarg = 'pk'
pagination_class = MyPagination
# rewrite create Implement the de duplication mechanism
def create(self, request, *args, **kwargs):
#1. Receive previous data
sku_id=request.data.get('sku')
image=request.data.get('image')
print(' Front end data :',sku_id,image)
#2. Judge the current product sku_id Did you add image This picture
sku_image=SKUImage.objects.filter(sku_id=sku_id,image=image)
if sku_image:
# Description has been added
return Response({
'code':400,
'msg':' This product has been added with this picture '
})
#3. When not added , Add pictures normally
obj=SKUImage.objects.create(sku_id=sku_id,image=image)
return Response({
'code':200,
'msg':' Picture added successfully ',
'data':self.get_serializer(obj).data
})
Configure the routing
from django.urls import path
from rest_framework import routers
from .views import *
urlpatterns = [
# Interface for uploading product pictures
path('upload/skuImage/',UploadSKUImageAPIView.as_view())
]
# Brand routing
router=routers.SimpleRouter()
router.register('skus',SKUAPIView,'skus') #sku The routing
router.register('specOption',SpecOptionViewSet,'specOption') # Specification options routing
router.register('skuImage',SKUImageViewSet,'skuImage') #
urlpatterns+=router.urls
front end
Find the corresponding veu Components , To configure
Realization sku Addition, deletion and modification of
for example :Pictures.vue Get all the data
<script> import BreadCrumb from '@/components/widget/BreadCrumb' // Add pictures of products import Addpictures from '@/components/widget/AddPictures' // Exhibition Delete Modify the product picture import PicturesTable from '@/components/widget/PicturesTable' export default {
name: 'Brands', data () {
return {
page:1, total:0, pagesize:3, aPicturesList:[] } }, components:{
BreadCrumb, Addpictures, PicturesTable }, mounted(){
this.fnGetData(1); }, methods:{
fnGetData(num){
this.axios.get('/v1/goods/skuImage/',{
params:{
page:num?num:this.page, pageSize:this.pagesize }, headers:{
Authorization:'JWT '+localStorage.token }, responseType:'json' }).then((result) => {
this.aPicturesList=result.data.results this.total=result.data.count }).catch((err) => {
console.log(' load sku Wrong picture ',err) }); }, fnGetPage(num){
this.page=num this.fnGetData(num) } } } </script>
for example :PicturesTable.vue Display and modify data
Modify the route in the event , Field etc.
<script> let token = localStorage.token; export default {
name: "OptionsTable", props: ["pictures"], data() {
return {
host:'http://127.0.0.1:8000', // When showing pictures, add uploaData: {
token: "", }, // Outside the chain address baseUrl: "http://r8isbvnn5.bkt.clouddn.com/", pop_show: false, sku_list: [], PicturesForm: {
sku: "", image: "", }, rulesPicturesForm: {
}, }; }, methods: {
// Click Edit to trigger fnPopShow(id) {
this.pop_show = true; this.edit_id = id; this.axios .get("/v1/goods/skuImage/" + this.edit_id + "/", {
headers: {
Authorization: "JWT " + token, }, responseType: "json", }) .then((res) => {
this.PicturesForm.sku = res.data.sku; this.PicturesForm.image = res.data.image; }) .catch((err) => {
console.log(' Correct the mistake ',err.response); }); }, // Submission of updates submitForm() {
this.axios .put("/v1/goods/skuImage/" + this.edit_id + "/", this.PicturesForm, {
headers: {
Authorization: "JWT " + token, }, responseType: "json", }) .then((res) => {
console.log(" Modified response 》》", res); if (res.status==200){
this.$message({
type: "success", message: " The product picture was modified successfully !", }); this.pop_show = false; this.$emit("fnResetTable"); this.resetForm("PicturesForm"); }else{
this.$message({
type: "error", message: " Failed to modify the product picture !", }); } }) .catch((err) => {
console.log(err.message); }); }, fnDelPictures(id) {
this.edit_id = id; this.$confirm(" This operation will delete the product picture , Whether or not to continue ?", " Tips ", {
confirmButtonText: " determine ", cancelButtonText: " Cancel ", type: "warning", }) .then(() => {
this.axios .delete("/v1/goods/skuImage/" + this.edit_id + "/", {
headers: {
Authorization: "JWT " + token, }, responseType: "json", }) .then((res) => {
if (res.status==204){
this.$message({
type: "success", message: " Delete picture succeeded !", }); this.$emit("fnResetTable"); }else{
this.$message({
type: "error", message: " Failed to delete picture !", }); } }) .catch((err) => {
if (err.response.status == 404) {
this.$message({
type: "info", message: " Picture not found !", }); } }); }) .catch(() => {
this.$message({
type: "info", message: " Delete cancelled ", }); }); }, // Load all sku fnGetSkuList() {
this.axios .get("/v1/goods/skus/", {
headers: {
Authorization: "JWT " + token, }, responseType: "json", }) .then((res) => {
console.log(' Load all sku',res); this.sku_list = res.data; }) .catch((err) => {
console.log(err.response); }); }, resetForm(formName) {
this.$refs[formName].resetFields(); }, // Click upload , How to trigger successful upload uploadSuccess(res, files, fiels_list) {
// res.key Get the address where the uploaded pictures are stored in qiniu cloud // Splice picture address console.log(" Upload updated pictures ", res,files); // this.imgUrl = this.baseUrl + res.key; this.PicturesForm.image='/'+res.static_path+'/'+files.name }, uploadError(err) {
console.log(' Upload failed ',err); }, }, mounted() {
this.fnGetSkuList(); this.uploaData.token=localStorage.token }, }; </script>
for example :AddPictures.vue Modify the data
Modify the route in the event , Field etc.
Add the field of binding foreign key to realize the drop-down box addition
Adding is similar to modifying acquired data
<script> let token = localStorage.token; export default {
name: "AddChannels", data() {
return {
host:'http://localhost:8000', pop_show: false, baseUrl: "http://r8isbvnn5.bkt.clouddn.com/", imgUrl: "", uploadData: {
token: "", }, sku_list: [], PicturesForm: {
sku: "", image: "", }, rulesBrandsForm: {
sku:[{
required:true,message:' Required sku'}], image:[{
required:true,message:' Required image'}] }, }; }, methods: {
// Submit submitForm() {
// Check the data this.$refs['PicturesForm'].validate((val)=>{
if(val){
this.axios .post("/v1/goods/skuImage/", this.PicturesForm, {
headers: {
Authorization: "JWT " + token, // "Content-Type": "multipart/form-data", }, responseType: "json", }) .then((res) => {
console.log(' Add product image ',res); if (res.data.code == 200) {
this.$message({
type: "success", message: " Picture added successfully !", }); this.pop_show = false; this.resetForm("PicturesForm"); this.$emit("fnResetTable"); }else{
this.$message({
type:'error', message:res.data.msg }) } }) .catch((err) => {
console.log(err.response); }); }else{
return false } }) }, // Get all sku fnGetSkuList() {
this.axios .get("/v1/goods/skus/", {
headers: {
Authorization: "JWT " + token, }, responseType: "json", }) .then((res) => {
console.log(' Load all sku goods ',res); this.sku_list = res.data; }) .catch((err) => {
console.log(err.response); }); }, resetForm(formName) {
this.$refs[formName].resetFields(); }, // Click upload , How to trigger successful upload uploadSuccess(res, files) {
console.log(" Upload successful ", res,files); // Splice picture address // this.imgUrl = this.baseUrl + res.key; this.PicturesForm.image='/'+res.static_path+'/'+files.name }, uploadError(err) {
console.log(' Upload failed :',err); }, }, mounted() {
this.uploadData.token=localStorage.token // Get all sku goods this.fnGetSkuList(); }, }; </script>
边栏推荐
- Background image related applications - full, adaptive
- 虚拟机克隆
- redis配置文件下载
- Vcenter7.0 managing esxi7.0 hosts
- On Valentine's day, I drew an object with characters!
- docker 安装mysql后进入容器内部发现登录不了mysql
- UVM入门实验1
- Block, there is a gap between the block elements in the row
- containerd拉取私库镜像失败(kubelet)
- 2022/7/26 exam summary
猜你喜欢
随机推荐
PHP realizes data interaction with MySQL
Element display mode: block level, inline, inline block, nesting specification, display mode conversion
The third letter to the little sister of the test | Oracle stored procedure knowledge sharing and test instructions
You may need an additional loader to handle the result of these loaders.
[golang] golang develops wechat official account web page authorization function
Breadth first search
Virtual machine cloning
[netding cup 2020 Qinglong group]areuserialz (buuctf)
Dormitory access control system made by imitating the boss (III)
Vcenter7.0 installation of ibm3650m4 physical machine
Database startup report error_ user_ connect_ times &gt; 0 error
[ciscn2019 southeast China division]web11 1
The response of the database interface is very slow
Bandwidth and currency
Teach you to build a nail warning robot hand in hand
[MRCTF2020]Ezpop 1
JS basic knowledge - daily learning summary ①
[geek challenge 2019] finalsql 1
"PHP Basics" uses echo statements to output information
vCenter7.0管理Esxi7.0主机





![[geek challenge 2019] finalsql 1](/img/a7/857d47639fcb38e0055a2444206b8c.png)



