Python自动化之form验证
model里面进行数据验证
- 在类里面定义一个clean方法
	class User(models.Model):
		def clean(self):
			#在这个可以做一些验证的操作
			pass
- 还可以手动抛出异常
from django.core.exceptions import ValidationError
	raise ValidationError(message="XX错误",code="i1")
clean方法的内容实际是空的,是Python预留的可以自定义的hooks
在view里面进行model验证
需要写上这个方法
obj.full_clean()
full_clean分为两步:
1. 正则验证,比如emailfield 会验证是否是邮箱格式的
2. 进行clean方法验证,而这个clean是存在model里面的,所以需要在model里面写		clean方法
form的choicefield
from django.forms.models import ModelChoiceField
class User(forms.Form):
	user_type = fields.ChoiceField(
        # choices=[(1,'普通用户'),(2,'超级用户'),],
        choices= [],
        widget=widgets.Select
    )
    user_type2 = fields.CharField(widget=widgets.Select(choices=[]))
    
    
    user_type3 = ModelChoiceField(
        empty_label='请选择用户类型',
        queryset=models.UserType.objects.all(),
        to_field_name='id'
    )
    
    def __init__(self,*args, **kwargs):
        super(UserInfoForm,self).__init__(*args, **kwargs)
        self.fields['user_type'].choices = models.UserType.objects.values_list('id','name')
        self.fields['user_type2'].widget.choices = models.UserType.objects.values_list('id','name')
重写构造方法,这样每次数据修改完之后就不需要重新运行程序了进行前端展示的更新
如果要使用ModelChoiceField的话需要,在models里面写
>def __str__(self):
>	return self.name
>```  
>如果不写的话,下拉框只会显示对象类型
**默认_\_str_\_**
    def __str__(self):
        if six.PY2 and hasattr(self, '__unicode__'):
            return force_text(self).encode('utf-8')
        return str('%s object' % self.__class__.__name__)
    感谢关注

 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号