【问题标题】:django filefield renaming issuedjango 文件域重命名问题
【发布时间】:2018-11-30 05:22:34
【问题描述】:

我正在使用以下代码为通过表单上传的模型中的 FileField 重命名文件名路径:

class Document(models.Model): document_date = models.DateField(null=True) document_category = models.CharField(null=False, max_length=255, choices=DOCUMENT_CATEGORY_CHOICES) document = models.FileField(upload_to='documents/', max_length=100) def save(self, *args, **kwargs): ext = os.path.splitext(self.document.name)[1] date = str(self.document_date).replace('-', '') category = self.document_category self.document.name = '%s_%s%s' % (date, category, ext) super().save(*args, **kwargs)

这对于创建的新记录很好,但是当我使用表单更新这些记录时,记录会保存有新的更新详细信息(日期和/或类别),并且我的数据库反映了新的文件名路径,但是文件名文件夹中的实际文件未更新。

有没有人能够阐明我哪里出错了,以及我可以如何解决这个问题?非常感谢任何帮助!

【问题讨论】:

    标签: django django-models django-forms django-file-upload


    【解决方案1】:

    这是因为save() 方法在每次更新操作时调用

    我从 OP 了解到的是,在两种情况下您只需要 save() 方法,
    1. 创建新条目时
    2. 当document 字段更改/更新时。
    所以,尝试如下更改save()

    class Document(models.Model): document_date = models.DateField(null=True) document_category = models.CharField(null=False, max_length=255, choices=DOCUMENT_CATEGORY_CHOICES) document = models.FileField(upload_to='documents/', max_length=100) def save(self, *args, **kwargs): if not self.id or not Document.objects.get(id=self.id).document == self.document: ext = os.path.splitext(self.document.name)[1] date = str(self.document_date).replace('-', '') category = self.document_category self.document.name = '%s_%s%s' % (date, category, ext) super().save(*args, **kwargs)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-06
      • 2013-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-10
      相关资源
      最近更新 更多