2016-09-17 151 views
1

用戶上傳2 .ini文件後,我想將它保存在以下文件夾中。如何將文件上傳到Django中的特定文件夾?

MEDIA/uploadedconfigs /打印機/塑料/

但是,它目前保存到下面的地址。

MEDIA/uploadedconfigs /無/


下面是上傳文件的代碼。
models.py

def UploadedConfigPath(instance, filename): 

    return os.path.join('uploadedconfigs', str(instance.id), filename) 

class ConfigFiles(models.Model): 

    Printer = models.CharField(_('Printer Model'), 
    max_length=100, blank=True, null=True, unique=False) 
    Plastic = models.CharField(_('Plastic'),  
    max_length=40, blank=True, null=True, unique=False) 
    creator = models.CharField(_('Creator'), 
    max_length=40, blank=True, null=True, unique=False) 
    HDConfig = models.FileField(_('High Detail'), 
    upload_to=UploadedConfigPath) 
    LDConfig = models.FileField(_('Low Detail'), 
    upload_to=UploadedConfigPath) 

    pub_date = models.DateTimeField(_('date_joined'), 
    default=timezone.now) 

我不是什麼「實例」是幹什麼的,但有人告訴我,這是什麼吐出了「無」的文件夾名稱。我也被告知我可能需要將這些文件放在一個臨時文件夾中,但我不確定會發生什麼。任何幫助,將不勝感激!

回答

1

你可以用這個替換功能UploadedConfigPath

def UploadedConfigPath(instance, filename): 
    return os.path.join('uploadedconfigs', 'Printer', 'Plastic', filename) 

編輯:

這應做到:

def UploadedConfigPath(instance, filename): 
    return os.path.join('uploadedconfigs', instance.Printer, instance.Plastic, filename) 
+0

我可能沒有明確。我試圖上傳到用戶輸入的變量'Printer'和'Plastic',如ModelClass所示。使用你的方法將上傳到實際稱爲'打印機'的文件夾,而不是用戶輸入變量。 – RknRobin

+0

@RknRobin是的,你還沒有真正清楚......無論如何,我編輯了我的答案。 –

+1

這正是我非常感謝的! – RknRobin

2

試圖通過設置參數設置使用原始的方法.py

MEDIA_ROOT = join(PROJECT_ROOT, '../media/')" 
MEDIA_URL = '/media/' 

在您的文件:

def UploadedConfigPath(instance, filename): 
     return os.path.join(settings.MEDIA_ROOT, 'uploadedconfigs/', str(instance.id), '/', filename) 
+0

我可能已經簡化了這個過多,但我正在使用這種方法,並將其全部包裝到上面顯示的變量MEDIA中。我的設置如上所示,並正確上傳到MEDIA_ROOT(無需設置.MEDIA_ROOT)。我的問題是(str(instance.id),文件名),只是輸出到文件夾'None' – RknRobin

+0

如果你沒有更新你的settings.py可以使用這個def UploadedConfigPath(實例,文件名): return os.path.join ('uploadedconfigs /',str(instance.id),'/',filename) – Sagar

相關問題