2016-07-05 26 views
0

的Django趕上unique_together在形式和不保存文件

class Document(models.Model): 
    profile = models.ForeignKey(Profile, null=True) 

    hash = models.CharField(max_length=100, blank=True) 
    name = models.CharField(max_length=100, blank=True) 
    url = models.CharField(max_length=100, blank=True) 

    file = models.FileField() 

    def __str__(self): 
     return str(self.id) 

    @property 
    def gen_url(self): 
     self.url = uuid.uuid4().hex 

    @staticmethod 
    def gen_digest(file): 
     m = hashlib.md5() 
     for chunk in read_by_chunk(file): 
      m.update(chunk) 
     digest = m.hexdigest() 
     return digest 

    class Meta: 
     unique_together = (('profile', 'hash'),) 

當我嘗試通過管理同一profiledocument創建的文檔,它通過Form返回一個錯誤。我認爲這是我想要達到的正確方式。

但是:

if form.is_valid(): 

    print 'valid' 
    try: 
     form.save() 
    except IntegrityError: 
     print 'unique error' 
     messages.add_message(request, messages.ERROR, u'already have') 
    return HttpResponseRedirect('/') 
else: 
    return HttpResponse('not valid') 

失敗的錯誤。

所以問題:

1)我怎麼能顯示messages寧可失敗IntegrityError

2)如何防止file存儲

回答

0

創建默認的ModelForm應該驗證的唯一性,除非該字段被排除。從django 1.9 source code

# self._validate_unique will be set to True by BaseModelForm.clean(). 
    # It is False by default so overriding self.clean() and failing to call 
    # super will stop validate_unique from being called. 

然後調用模型實例的validate_unique方法。然而,提防exclude疑難雜症的 - 因爲每docs

Model.validate_unique(exclude=None)

這種方法類似於clean_fields(),但驗證你的模型,而不是單個字段值的所有唯一性約束。可選的exclude參數允許您提供要從驗證中排除的字段名稱列表。如果任何字段未通過驗證,它將引發ValidationError。

請注意,如果您向validate_unique()提供排除參數,則不會檢查涉及您提供的某個字段的任何unique_together約束。

如果全部失敗,你可以在你的窗體的clean方法明確​​

調用