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

标签 django

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

最佳答案

django/forms/forms.py

is_valid 表单方法正在从表单 _get_errors 调用表单 full_clean 方法(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/forms/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() 执行额外的调用.

关于django - 如何手动将模型字段验证器连接到表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14865680/

相关文章:

python - 如果引发异常,测试会失败吗?

django - 在 Ubuntu 中使用 nginx 和 uwsgi 运行 Django 的问题

django - Wagtail:如何覆盖数据库中的 HTML 标记输出。使用 <strong> 或 <em> 而不是 <b> 或 <i> 作为富文本模板标签

Django gunicorn nginx (111 : Connection refused) while connecting to upstream

json - 如何使用 Django Rest Framework 反序列化嵌套对象

带有 Jinja2 : Contrib app Admin not working 的 Django 1.8

python - 如何修复 : 'TypeError: expected string or bytes-like object' when doing unit test on a views. py 函数

mysql - 无法在本地开发服务器上通过 Angular 2 中的 HTTP POST 发布数据

css - 通过这种技术优化前端加载

python - 使用 ._meta Django