美文网首页
django-form验证流程

django-form验证流程

作者: 葡萄柚子茶 | 来源:发表于2020-05-26 14:36 被阅读0次

在form中定义def clean_字段的方法
增加自定义验证

class MachineForm(forms.ModelForm):

    class Meta:
        model = Machine
        fields = ['hostname', 'ip', 'port', 'account', 'password', 'platform', 'memory',
                  'disk_info', 'cpu_model', 'share_users', 'data_file_path', 'workspace_file_path']
        error_messages = {
            'hostname': {
                'unique': "此名称已存在"
            },
            'data_file_path': {
                'invalid': "路径格式不正确"
            }

        }
        widgets = {
            'share_users': forms.SelectMultiple(attrs={
                'class': 'select2', 'data-placeholder': '用户'
            }),
        }
#定义局部钩子,用来校验data_file_path字段
    def clean_data_file_path(self):
        data_file_path = self.data.get('data_file_path')
        if not os.path.isdir(data_file_path):
            raise forms.ValidationError(message='该路径输入有误', code='invalid')
        return data_file_path

打断点进入django中的forms.py文件

def _clean_fields(self):
  ...
  try:
    pass
  except ValidationError as e:
    self.add_error(name, e)

将自定义验证方法def clean_data_file_path中报错信息添加到_errors中
Django——form组件is_valid校验机制
Django中Model-Form验证
Django:Form和ModelForm介绍
Django数据校验
is_valid()方法,自动校验同名的数据。
clean()方法是获取验证通过的字段的方法。
error()方法是获取验证失败的字段的失败信息

相关文章

网友评论

      本文标题:django-form验证流程

      本文链接:https://www.haomeiwen.com/subject/tjumahtx.html