kjarsenal
kjarsenal

Reputation: 934

dynamic upload field arguments

if I have basic model for keeping track of client art:

class ArtEntry(models.Model):
    client = models.CharField(max_length=50, choices=CLIENT_CHOICES)
    job_number = models.CharField(max_length=30, unique=False, blank=False, null=False)
    filename = models.CharField(max_length=64, unique=False, blank=False, null=False)
    descriptor = models.CharField(max_length=64, unique=False, blank=True, null=True)
    date = models.DateField(("Date"), default=datetime.date.today)
    post_type = models.CharField(max_length=64, choices=POST_CHOICES)

and the last field of this model is a file upload field:

    upload = models.FileField(upload_to='documents/*/**/***')

is it possible to populate the "upload_to" argument dynamically, so that * = the input 'client' data and ** = the input 'job_number' and * = the 'post_type' choice?

Upvotes: 0

Views: 139

Answers (2)

user1151618
user1151618

Reputation:

One Example;

def image_path(self, uploaded_file_name):
    prefix = 'documents/'
    extension = os.path.splitext(uploaded_file_name)[-1]
    if self.pk != None:
        return prefix + str(self.pk) + extension
    else:
        tmp_name = str(uuid.uuid4())
        self.temp_image = prefix + tmp_name + extension
        return self.temp_image

image_upload = models.ImageField(upload_to=image_path, null=True, blank=True) 

You should use python functions.

Upvotes: 0

arie
arie

Reputation: 18982

Sure. Just check the docs for upload_to:

This may also be a callable, such as a function, which will be called to obtain the upload path, including the filename.

Check this answer to see an example which you can easily adapt to your problem.

Upvotes: 1

Related Questions