如何手动将模型字段验证器连接到表单字段

时间:2013-02-14 00:11:25

标签: django

我相信modelform知道如何使用模型字段验证器。我正在创建一个动态表单,我需要复制此行为,所以我不违反DRY。我在哪里连接这两个?

1 个答案:

答案 0 :(得分:2)

<强> django的/形式/ forms.py

is_valid表单方法在此处full_clean表单_get_errors调用表单self.errors=property(_get_errors)方法:

return self.is_bound and not bool(self.errors)

full_clean调用这一系列函数:

self._clean_fields()
self._clean_form()
self._post_clean()

在这里你想要的功能我想:

def _post_clean(self):
    """
    An internal hook for performing additional cleaning after form cleaning
    is complete. Used for model validation in model forms.
    """
    pass

<强> django的/形式/ models.py

def _post_clean(self):
    opts = self._meta
    # Update the model instance with self.cleaned_data.
    self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)

    exclude = self._get_validation_exclusions()

    # Foreign Keys being used to represent inline relationships
    # are excluded from basic field value validation. This is for two
    # reasons: firstly, the value may not be supplied (#12507; the
    # case of providing new values to the admin); secondly the
    # object being referred to may not yet fully exist (#12749).
    # However, these fields *must* be included in uniqueness checks,
    # so this can't be part of _get_validation_exclusions().
    for f_name, field in self.fields.items():
        if isinstance(field, InlineForeignKeyField):
            exclude.append(f_name)

    # Clean the model instance's fields.
    try: 
        self.instance.clean_fields(exclude=exclude)
    except ValidationError, e:
        self._update_errors(e.message_dict)

    # Call the model instance's clean method.
    try: 
        self.instance.clean()
    except ValidationError, e:
        self._update_errors({NON_FIELD_ERRORS: e.messages})

    # Validate uniqueness if needed.
    if self._validate_unique:
        self.validate_unique()

因此,模型表单验证与简单表单验证的不同之处在于对模型instance._clean_fields(exclude=exclude)(某些字段从验证中排除)和instance.clean()执行其他调用。