在django管理区域中抛出ValidationError之后,无法更改模型实例 [英] Cannot change model instance after a ValidationError is thrown in django admin area

查看:122
本文介绍了在django管理区域中抛出ValidationError之后,无法更改模型实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下这样的模式:

class CFile(models.Model):
   filepath   = models.FileField(upload_to=...)
   collection = models.ForeignKey("FileCollection",null=True)
   ... # other attributes that are not relevant

   def clean(self):
     bname = os.path.basename
     if self.collection:
       cfiles = self.baseline.attachment_set.all()
       with_same_basename = filter(lambda e: bname(e.filepath.path) == bname(self.filepath.path),cfiles)
       if len(with_same_basename) > 0:
         raise ValidationError("There already exists a file with the same name in this collection")   

class FileCollection(models.Model):
  name = models.CharField(max_length=255)
  files= models.ManyToManyField("CFile")

如果已经存在具有相同基本名称的CFile,则禁止上传CFile,这就是为什么我添加了 clean 。问题是:

I want to disallow the upload of a CFile if there already exists a CFile with the same basename, that's why I added the clean. The problem is:


  • 我上传了一个CFile,名称为 file1.png - >上传,因为没有其他具有此名称的文件存在

  • 我上传另一个CFile,名称为 file1.png - > I得到我已经有这个名称的文件的预期错误。所以,我尝试更改文件,并上传不同名称的文件( file2.png )。问题是,我通过pdb在clean中停止,模型实例仍然是 file1.png 。我想象这是因为我的ValidationError和django允许我纠正我的错误。问题是,如果我无法上传另一个文件,我无法纠正。如何处理这个?

  • I upload a CFile, with the name file1.png -> gets uploaded because no other files with this name exist
  • I upload another CFile, with the name file1.png -> I get the expected error that I already have a file with this name. So, I try to change the file, and upload a file with a different name ( file2.png ). The problem is, I stopped via pdb in the clean, and the model instance is still file1.png. I imagine this happens because of my ValidationError and django allows me to "correct my mistake". The problem is I cannot correct it if I cannot upload another file. How can I handle this?

编辑:这在管理区域发生,不幸的是忘记提到这一点。我没有任何定制(除了 inlines = [FileInline] )。

This happens in the admin area, sorry for forgetting to mention this before. I don't have anything custom ( besides inlines = [ FileInline ] ).

推荐答案

我认为最简单的方法是在你的模型中声明另一个字段的文件名,并使其对于每个集合都是唯一的。像这样:

I think the clearest way is to declare another field in your model for filename and make it unique for every collection. Like this:

class CFile(models.Model):
   filepath   = models.FileField(upload_to=...)
   collection = models.ForeignKey("FileCollection",null=True, related_name='files')
   filename = models.CharField(max_length=255)
   ... # other attributes that are not relevant

    class Meta:
        unique_together = (('filename', 'collection'),)

    def save(self, *args, **kwargs):
        self.filename = bname(self.filepath.path)
        super(CFile, self).save(args, kwargs)

这篇关于在django管理区域中抛出ValidationError之后,无法更改模型实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆