在views中
創(chuàng)新互聯(lián)建站主營河源網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,手機(jī)APP定制開發(fā),河源h5重慶小程序開發(fā)公司搭建,河源網(wǎng)站營銷推廣歡迎河源等地區(qū)企業(yè)咨詢
from django.shortcuts import render # Create your views here. from rest_framework.viewsets import ViewSetMixin from rest_framework.views import APIView from rest_framework.response import Response from app01 import Myser from app01 import models from app01.myutils.Myresponse import Responseone class Book(ViewSetMixin,APIView): def get_book(self,request,*args,**kwargs): ret=models.Book.objects.all() ser=Myser.BookSer(instance=ret,many=True) return Response(ser.data) def set_book(self,request,*args,**kwargs): myres=Responseone() print(request.data) ser=Myser.BookSer(data=request.data) if ser.is_valid(): ser.save() myres.msg='創(chuàng)建成功' else: myres.status=400 myres.msg=ser.errors return Response(myres.get_dic) def change_book(self,request,pk,*args,**kwargs): print(pk) myres = Responseone() ret = models.Book.objects.all().filter(pk=pk).first() ser = Myser.BookSer(instance=ret,many=False,data=request.data) # 傳instance和data是進(jìn)行修改 if ret: if ser.is_valid(): ser.save() myres.msg = '修改成功' else: myres.status=401 myres.msg = ser.errors print(ser.errors) print(Response(myres.get_dic)) else: myres.msg='用戶不存在' myres.status=403 return Response(myres.get_dic) 在路由中 url(r'^book/(?P<pk>\d+)', views.Book.as_view({'get':'get_book','put':'change_book','post':'set_book'})), 在校驗類中 校驗的是前臺傳過來的數(shù)據(jù) from rest_framework.exceptions import ValidationError from app01 import models from rest_framework import serializers class BookSer(serializers.ModelSerializer): class Meta: model=models.Book fields='__all__' print(fields) name=serializers.CharField(max_length=4,min_length=2,required=True,error_messages={'max_length':'最長為4','min_length':'最短為2','required':'姓名必須填寫'}) # 局部鉤子: def validate_name(self, value): # print(value) if value.startswith('sb'): # 不能以sb開頭 raise ValidationError('不能以sb開頭') else: return value # 全局鉤子找到了 def validate(self, value): # value是所有校驗通過數(shù)據(jù)的字典 print(value) name = value.get('name') price = value.get('price') if name and price: if str(name) == str(price): return value else: raise ValidationError('名字跟價格不相等') return value
網(wǎng)站欄目:rest_framework序列化組件校驗
瀏覽地址:http://jinyejixie.com/article30/ghhcso.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供外貿(mào)建站、面包屑導(dǎo)航、網(wǎng)站策劃、營銷型網(wǎng)站建設(shè)、靜態(tài)網(wǎng)站、Google
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)