Jake Rankin
Jake Rankin

Reputation: 744

What is the appropriate way to use a ModelForm field as an argument to upload_to?

I have a ModelForm, where two of the fields are lastname and firstname. I also have a file field for file uploading. As several files are being uploaded by many different people, I would like to group the files into a directory based on their names.

I've been trying to use a custom formatted string to do this, but so far I'm getting an error that there are not enough arguments for format string, and I am wondering if it as something to do with the form not being saved yet.

My attempt to generate a filename based on form fields is:

def filename_path(instance, filename):
     return os.path.join('applicant_documents/%s_%s/%s' % instance.last_name, instance.first_name, filename)

and the field from my model is defined as:

documents = models.FileField(upload_to=filename_path)

Am I doing something wrong, or is this not possible?

Upvotes: 2

Views: 67

Answers (1)

minglyu
minglyu

Reputation: 3327

As the error suggested, you need to provide a tuple instead for string formatting.

def filename_path(instance, filename):
     return os.path.join('applicant_documents/%s_%s/%s' % (instance.last_name, instance.first_name, filename))

Upvotes: 1

Related Questions