Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Upload a file in a folder whose value is selected through a list of choices

I have the following Script model :

from django.db import models
import os

    
def getListOfFiles(dirName):
    listOfFile = os.listdir(dirName)
    allFiles = list()
    for entry in listOfFile:
        fullPath = os.path.join(dirName, entry)
        if os.path.isdir(fullPath):
            allFiles.append((fullPath, entry))
    return allFiles


class Script(models.Model):
    script_name = models.CharField(max_length=200, blank=True)
    folder = models.CharField(choices=getListOfFiles('media/scripts'), max_length=200)
    file = models.FileField(upload_to=f'scripts/{folder}')

    def __str__(self):
        return self.script_name

I want to upload the script to the value of the attribute folder selected by the user through a list of choices.

With the upload_to=f'scripts/{folder}' it tries to upload it to media\scripts\<django.db.models.fields.CharField> which is obviously not what I want. I saw a bunch of people using a get_folder_display() function but is doesn’t seem to work in models, or I did it wrong.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I get the value of folder selected by the user ?

>Solution :

You can pass a function to upload_to, this function receives the instance and filename and must return the desired path including the filename.

Since the function will be passed the instance you can get the folder attribute

def script_upload_path(instance, filename):
    return f'scripts/{instance.folder}/{filename}'


class Script(models.Model):
    script_name = models.CharField(max_length=200, blank=True)
    folder = models.CharField(choices=getListOfFiles('media/scripts'), max_length=200)
    file = models.FileField(upload_to=script_upload_path)

You could consider using a FilePathField for your folder field

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading