django form組件擴展
阿新 • • 發佈:2018-09-03
exc 整體 objects 序列 orm 序列化 root exce val
1簡單擴展
利用form組件自帶的正則擴展:
a.方式一
from django.forms import Form from django.forms import widgets from django.forms import fields from django.core.validators import RegexValidator class MyForm(Form): user = fields.CharField( error_messages={‘invalid‘: ‘...‘}, validators=[RegexValidator(r‘^[0-9]+$‘, ‘請輸入數字‘), RegexValidator(r‘^159[0-9]+$‘, ‘數字必須以159開頭‘)], )
b.方式二
from django.forms import Form from django.forms import widgets from django.forms import fields from django.core.validators import RegexValidator class MyForm(Form): user = fields.RegexField(r‘^[0-9]+$‘,error_messages={‘invalid‘: ‘...‘})
2基於源碼流程
a.單字段驗證
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError class AjaxForm(forms.Form): username = fields.CharField() user_id = fields.IntegerField( widget=widgets.Select(choices=[(0,‘alex‘),(1,‘劉皓宸‘),(2,‘楊建‘),]) ) # 自定義方法 clean_字段名 #必須返回值self.cleaned_data[‘username‘] # 如果出錯:raise ValidationError(‘用戶名已存在‘) def clean_username(self): v = self.cleaned_data[‘username‘] if models.UserInfo.objects.filter(username=v).count(): # 整體錯了 # 自己詳細錯誤信息 raise ValidationError(‘用戶名已存在‘) return v def clean_user_id(self): return self.cleaned_data[‘user_id‘]
b.整體錯誤驗證
class AjaxForm(forms.Form): username = fields.CharField() user_id = fields.IntegerField( widget=widgets.Select(choices=[(0,‘alex‘),(1,‘劉皓宸‘),(2,‘楊建‘),]) ) # 自定義方法 clean_字段名 # 必須返回值self.cleaned_data[‘username‘] # 如果出錯:raise ValidationError(‘用戶名已存在‘) def clean_username(self): v = self.cleaned_data[‘username‘] if models.UserInfo.objects.filter(username=v).count(): # 整體錯了 # 自己詳細錯誤信息 raise ValidationError(‘用戶名已存在‘) return v def clean_user_id(self): return self.cleaned_data[‘user_id‘] def clean(self): value_dict = self.cleaned_data v1 = value_dict.get(‘username‘) v2 = value_dict.get(‘user_id‘) if v1 == ‘root‘ and v2==1: raise ValidationError(‘整體錯誤信息‘) return self.cleaned_data
2 django序列化
序列化 queryset的類型 需要用django自帶的
from django.core import serializers import json def get_data(request): ret = {‘status‘: True} userlist = models.Student.objects.all() ret[‘data‘] = serializers.serialize(‘json‘, userlist) return HttpResponse(json.dumps(ret))
django form組件擴展