gpt4 book ai didi

python Django : How to upload a file with a filename based on instance pk

转载 作者:太空狗 更新时间:2023-10-30 01:22:01 27 4
gpt4 key购买 nike

我有一个我认为很简单的问题。在我的模型中,我有一个 models.ImageField,它看起来像这样:

class CMSDocument(BaseItem):
thumb = models.ImageField(upload_to= './media/',blank=True)

但我想将它上传到 '.media/' + self.pk+ '.png' 我试图在模型的保存方法中更新字段,但这不起作用,因为调用“保存”时不知道 pk。我还尝试按照此处的建议为 upload_to 添加自定义函数:Django: Any way to change "upload_to" property of FileField without resorting to magic? .但这只会让这个领域空着。我能做什么?

编辑:我使用 Django 1.6

编辑:我使用了一个不太好的 post_save 信号:

def video_embed_post_save(sender, instance=False, **kwargs):    
document = DocumentEmbedType.objects.get(pk=instance.pk)
new_thumb = "media/%s.png" % (document.pk,)
if not document.thumb == new_thumb:
document.thumb = new_thumb
document.save()
...

最佳答案

主键由数据库分配,因此您必须等到模型行保存在数据库中。

首先将你的数据分成两个模型,子模型上有缩略图:

from django.db import models

from .fields import CMSImageField


class CMSDocument(models.Model):
title = models.CharField(max_length=50)


class CMSMediaDocument(CMSDocument):
thumb = CMSImageField(upload_to='./media/', blank=True)

如您所见,我为缩略图使用自定义字段而不是 ImageField。

然后创建一个fields.py文件,你应该覆盖ImageField继承的FileField类的pre_save函数:

from django.db import models


class CMSImageField(models.ImageField):
def pre_save(self, model_instance, add):

file = super(models.FileField, self).pre_save(model_instance, add)

if file and not file._committed:
# Commit the file to storage prior to saving the model
file.save('%s.png' % model_instance.pk, file, save=False)
return file

因为 CMSMediaDocument 继承自 CMSDocument 类,在调用 pre_save 时,渐进式 PK 已经保存在数据库中,因此您可以从 model_instance 中提取 pk。

我测试了代码,应该可以正常工作。

测试中使用的管理文件:

from django.contrib import admin

from .models import CMSMediaDocument

admin.site.register(CMSMediaDocument)

关于 python Django : How to upload a file with a filename based on instance pk,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27207065/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com