ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] >[success] # 直接和数据库字段关联 ~~~ from django import forms from .models import Student class StudentForm(forms.ModelForm): use_required_attribute = False def clean_phone(self): clean_data = self.cleaned_data['phone'] try: return int(clean_data) except ValueError: raise forms.ValidationError('必须为数1字') # def clean_qq(self): # cleaned_data = self.cleaned_data['qq'] # print(type(cleaned_data)) # if not cleaned_data.isdigit(): # raise forms.ValidationError("必须是数字") # return int(cleaned_data) class Meta: model = Student fields = ( "name",'sex','profession', "email","qq","phone" ) ~~~ >[info] ## 知识点 >[danger] ##### 关联数据库验证--forms.ModelForm ~~~ from django import forms from .models import Student class StudentForm(forms.ModelForm): class Meta: # 关联的数据库名称 model = Student # 关联的字段 fields = ( "name",'sex','profession', "email","qq","phone" ) ~~~ >[danger] ##### 两种思路验证数字 ~~~ def clean_phone(self): clean_data = self.cleaned_data['phone'] try: return int(clean_data) except ValueError: raise forms.ValidationError('必须为数1字') # def clean_qq(self): # cleaned_data = self.cleaned_data['qq'] # print(type(cleaned_data)) # if not cleaned_data.isdigit(): # raise forms.ValidationError("必须是数字") # return int(cleaned_data) ~~~