RknRobin RknRobin - 2 months ago 19
Python Question

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!

Answer

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)