Django:在save()期间填充字段
下面的模型包含一个Django:在save()期间填充字段,django,django-models,django-admin,Django,Django Models,Django Admin,下面的模型包含一个文件字段,其中用户提供了一个包含图片的zip文件。在保存过程中,通过名为process\u zipfile()的方法处理此zip文件 class Album(models.Model): nom = models.CharField(max_length = 200) added_by = models.ForeignKey(User, null=True, blank=True) gallery = models.ForeignKey(Gallery, nu
文件字段
,其中用户提供了一个包含图片的zip文件。在保存过程中,通过名为process\u zipfile()
的方法处理此zip文件
class Album(models.Model):
nom = models.CharField(max_length = 200)
added_by = models.ForeignKey(User, null=True, blank=True)
gallery = models.ForeignKey(Gallery, null=True, blank=True)
zip_file = models.FileField('image field .zip', upload_to=PHOTOLOGUE_DIR+"/temp",
help_text='Select a .zip file of images to upload into a new Gallery.')
class Meta:
ordering = ['nom']
def save(self, *args, **kwargs):
self.gallery = self.process_zipfile()
super(Album, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
photos = self.gallery.photos.all()
for photo in photos:
photo.delete()
self.gallery.delete()
super(Album, self).delete(*args, **kwargs)
def process_zipfile(self):
if os.path.isfile(self.zip_file.path):
......(creates gallery object and links the photos)
return gallery
它可以正常工作,但字段库
(表单留空)没有由进程创建的库填充。我做错了什么
此外,删除方法似乎不起作用,你知道吗?我终于能够使用post\u save
和pre\u delete
解决我的问题了:
def depacktage(sender, **kwargs):
obj = kwargs['instance']
obj.gallery = obj.process_zipfile()
obj.zip_file = None
post_save.disconnect(depacktage, sender=Album)
obj.save()
post_save.connect(depacktage, sender=Album)
def netoyage(sender, **kwargs):
obj = kwargs['instance']
if obj.gallery:
if obj.gallery.photos:
photos = obj.gallery.photos.all()
for photo in photos:
photo.delete()
gal = Gallery.objects.get(pk = obj.gallery.pk)
pre_delete.disconnect(netoyage, sender=Album)
gal.delete()
pre_delete.connect(netoyage, sender=Album)
pre_delete.connect(netoyage, sender=Album)
post_save.connect(depacktage, sender=Album)
虽然这个问题已经问了两年了,但我在尝试学习如何做类似的事情时遇到了它
在保存模型或字段之前,上载的文件不会写入其永久位置,因此路径可能会产生误导。根据您的配置和文件大小,它通常位于RAM(如果小于2.5 MB)或tmp
目录中。详情请参阅:
如果需要在保存模型之前获取文件句柄,以便对其执行某些处理,可以在字段上调用save
(它包含两个参数,文件名和表示其内容的文件对象,请参见:)
由于您将在save()中调用save(),因此您可能希望传递可选的save=False
(假设您在模型的下面某处调用save()
)
OP的解决方案之所以有效,是因为保存模型后会调用post save
处理程序,因此文件存在于预期位置
替代解决方案:强制使用tmp文件处理程序处理文件,并获取tmp路径;实现您自己的上载处理程序。您的process_zipfile()返回类型是什么?你确定它是Gallery模型类型吗?@kesun:yes是使用Gallery=Gallery.objects.create(title=self.nom,title\u slug=slugify(self.nom))
关于删除方法:有时(特别是通过django admin删除时)从未调用此方法。最好使用pre_delete/post_delete信号,以确保在delete中要执行的操作始终完成。