zoukankan      html  css  js  c++  java
  • Python自动化之form验证

    model里面进行数据验证

    1. 在类里面定义一个clean方法
    	class User(models.Model):
    		def clean(self):
    			#在这个可以做一些验证的操作
    			pass
    
    1. 还可以手动抛出异常
    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__)
  • 相关阅读:
    java.utils.HashMap数据结构分析(转)
    oracle什么时候须要commit
    CreateFont具体解释
    Java工厂模式
    簡單SQL存儲過程實例
    Cocos2d-x 3.0新引擎文件夹结构
    设计模式之十 适配器模式
    腰围2尺1,2,3,4,5,6,7,8寸各自等于是多少厘米/英寸(对比表)
    iOS 基础函数解析
    内部元素一一相应的集合的算法优化,从list到hashmap
  • 原文地址:https://www.cnblogs.com/wspblog/p/6359147.html
Copyright © 2011-2022 走看看