Django在Form中捕获unique_together而不保存文件

时间:2016-07-05 07:21:02

标签: django django-models django-forms django-views

我有

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

1 个答案:

答案 0 :(得分: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()提供exclude参数,则不会检查涉及您提供的某个字段的任何unique_together约束。

如果全部失败,您可以明确调用表单的clean方法self.instance.validate_unique()