2017-01-02 62 views
0

instance.id返回None上傳圖片時通過管理頁面。這個想法是將每個住所的所有圖像上傳到不同的文件夾。這裏是我的代碼:django instance.id =上傳圖片時無

models.py

from django.db import models 
import os 

def get_image_path(instance, filename): 
    return os.path.join('photos', "residence_%s" % instance.id, filename) 


# Create your models here. 
class Residence(models.Model): 
    big_image = models.ImageField("Main Image",upload_to=get_image_path) 
    small_images = models.ImageField("Small Images",upload_to=get_image_path, blank=True, null=True) 

settings.py

MEDIA_URL = '/media/' 

編輯:如果我修改圖像已被加入模型後,它的工作原理。

+0

用,因爲實例尚未保存instance.pk –

+0

還是返回無 –

+0

這是沒有嘗試在那時候。 –

回答

-1

另一種不錯的方式來解決這個問題,需要更少的代碼是有您的模型使用主鍵的UUID而不是數據庫生成的ID。這意味着模型在第一次保存時已經是已知的UUID,並且可以與任何upload_to回調一起使用。

所以對於原來的例子,你會做這樣的事情

from django.db import models 

import uuid 
import os 

def get_image_path(instance, filename): 
    return os.path.join('photos', "residence_%s" % str(instance.id), filename) 

# Create your models here. 
class Residence(models.Model): 
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) 
    big_image = models.ImageField("Main Image",upload_to=get_image_path) 
    small_images = models.ImageField("Small Images",upload_to=get_image_path, blank=True, null=True) 

Django's UUIDField reference更多信息