2016-08-13 70 views
1

Django的1.10的ModelForm和unique_together驗證

的文件建立說的ModelForm一起驗證獨特如果清潔方法是否正確覆蓋。 https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#overriding-the-clean-method

我做了一些錯誤,因爲unique_together驗證不起作用。

>>> from wiki.models import Wiki 
>>> Wiki.objects.all() 
<QuerySet [<Wiki: image/1/fdfff>, <Wiki: image/1/fdffff>]> 

where image is related_model and 1 is related_id。

你能幫我理解這個重寫有什麼問題嗎?

class WikiForm(ModelForm): 
    class Meta: 
     model = Wiki 
     fields = ['related_model', 'related_id', 'article'] 
     unique_together = (("related_model", "related_id"),) 

    def validate_related_model(self): 
     ... 

    def validate_related_id(self): 
     ... 

    def clean(self): 
     self.validate_related_model() 
     self.validate_related_id() 

     # To maintain unique_together validation, 
     # we must call the parent class’s clean() method. 
     return super(WikiForm, self).clean() 

回答

2

unique_together是一個數據庫級約束。它應該在模型的Meta類中指定,而不是模型形式。爲使驗證工作正常,請將其移至Wiki模型。在你的表單中,你可能甚至不需要有那些額外的驗證方法。

這看起來並不適用於您,但也請注意,爲了使獨特驗證正常工作,您的模型表單必須包含在unique_together約束中指定的所有字段。所以,如果related_modelrelated_id從形式排除在外,你需要做一些額外的工作,以使正確的驗證情況發生:

def validate_unique(self): 
    # Must remove organization field from exclude in order 
    # for the unique_together constraint to be enforced. 
    exclude = self._get_validation_exclusions() 
    exclude.remove('organization') 

    try: 
     self.instance.validate_unique(exclude=exclude) 
    except ValidationError, e: 
     self._update_errors(e.message_dict) 

在上面的例子中,我從形式的列表中刪除organization排除字段,因爲它是unique_together約束的一部分。

+0

非常感謝。 – Michael