#商品分类的反序列化
class CategoryUnSerializer(serializers.Serializer):
#约束
name = serializers.CharField(max_length=32)
#添加
def create(self, validated_data):
return models.Category.objects.create(**validated_data)
from rest_framework.views import APIView
from rest_framework.response import Response
from . import models
from . serializers import *
#商品分类
class CateView(APIView):
def post(self, request):
obj = CategoryUnSerializer(data=request.data) #调用反序列化
if obj.is_valid(): #如果通过约束
obj.save() #执行反序列化中的create方法
return Response({
'status':200,
'msg':'',
'data':''
})
return Response({
'status': 201,
'msg': '添加失败',
'data': ''
})
<template>
<div id="addcate">
<p>分类名称<input type="text" v-model="catename"></p>
<button @click="sub">添加</button>
</div>
</template>
<script>
export default {
name:'addcate',
data() {
return {
catename:'' //初始
}
},
methods:{
sub:function(){
this.axios({
url:'/api/app01/cate/',
method:'post',
data:{'name':this.catename}
}).then(res=>{
if(res.data.status==200){
alert('添加成功')
}else{
alert(res.data.msg)
}
})
}
}
}
import addcate from '@/components/AddCate'
{
path: '/addcate',
name: 'addcate',
component: addcate
},