2

modelform はモデル フィールド バリデータの使い方を知っていると思います。動的フォームを作成していますが、DRY に違反しないように、この動作を複製する必要があります。この 2 つをどこで接続しますか?

4

1 に答える 1

2

ジャンゴ/フォーム/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

ジャンゴ/フォーム/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()ます。

于 2013-02-15T10:31:15.853 に答える