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

Time:05-05

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.

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

CodePudding user response:

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

  • Related