2016-09-17 254 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

相关问题