2011-03-15 71 views
1

我有以下模型,其中包含FileField,其中用户提供包含图片的zip文件。在保存期间,该zip文件通过名为process_zipfile()的方法进行处理。Django:保存期间填充字段()

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 

它工作的很好,除了现场gallery(由左表格空白)不是由process_zipfile()创建画廊填充。我做错了什么?

此外,删除方法似乎没有工作,任何想法?

+0

process_zipfile()的返回类型是什么?你确定它是Gallery模型类型吗? – 2011-03-15 16:40:41

+0

@kesun:是使用'gallery = Gallery.objects.create(title = self.nom,title_slug = slugify(self.nom))' – Mermoz 2011-03-15 17:10:20

+2

关于删除方法:有时(特别是当你通过django-admin删除时)方法永远不会被调用。更好地使用pre_delete/post_delete信号来确保您想要在删除中执行的操作始终完成。 – 2011-03-16 10:06:05

回答

0

我终于能够解决使用post_savepre_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) 
0

虽然这个问题是两岁我碰到它努力学习如何做同样的事情。

上传的文件不会写入其永久位置,直到模型或字段被保存,因此路径可能会引起误解。根据您的配置和文件大小,它通常位于RAM(如果小于2.5 MB)或tmp目录中。有关详细信息,请参阅: https://docs.djangoproject.com/en/dev/topics/http/file-uploads/#where-uploaded-data-is-stored

如果您需要获取有关文件句柄,保存之前的模型,以做它的一些处理,你可以打电话场上save(它需要两个参数,文件名和表示其内容的File对象,请参阅:https://docs.djangoproject.com/en/1.2/ref/models/fields/#django.db.models.FieldFile.save)。因为你会在save()中调用save(),所以你可能想要通过可选的save=False(假设你在模型的某个位置上调用save())。

由于在保存模型后调用post-save处理程序,所以OP的解决方案奏效,因此该文件存在于预期位置。

备用解决方案:强制使用tmp文件处理程序处理文件,并获取tmp路径;实现你自己的上传处理程序