2013-02-14 71 views
2

我相信,modelform知道如何使用模型字段驗證程序。我正在創建一個動態表單,我需要複製這個行爲,所以我不違反DRY。我在哪裏連接這兩個?如何手動將模型字段驗證程序連接到表單字段

+1

如果您提供了代碼的相關部分,這將更容易回答。 – mVChr 2013-02-14 00:21:45

+0

我會嘗試構建一個簡單的例子 – danatron 2013-02-14 01:02:29

回答

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()