2011-03-15 69 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路徑;實現你自己的上傳處理程序