RknRobin
RknRobin

Reputation: 401

How do I upload files to a specific folder in Django?

After the user uploads 2 .ini files, I would like it to save both files inside the following folder.

MEDIA/uploadedconfigs/Printer/Plastic/

However, it's currently saving to the address below.

MEDIA/uploadedconfigs/None/


Below is the code that uploads the files.
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)

I'm not what "instance" is doing, but I was told it's what is spitting out the "None" folder name. I was also told I may need to place the files in a temporary folder but I'm not sure what that would entail. Any help would be appreciated!

Upvotes: 1

Views: 1997

Answers (2)

Loïc
Loïc

Reputation: 11943

You could replace the function UploadedConfigPath with this :

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

Edit :

This should do it :

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

Upvotes: 1

Sagar
Sagar

Reputation: 1155

try to use original approach by setting parameter in settings.py

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

In your file:

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

Upvotes: 2

Related Questions