To with upload_to determined at runtime with a Python Django FileField, we can set the upload_to path dynamically in a FileField.
For instance, we write
def content_file_name(instance, filename):
return '/'.join(['content', instance.user.username, filename])
class Content(models.Model):
name = models.CharField(max_length=200)
user = models.ForeignKey(User)
file = models.FileField(upload_to=content_file_name)
to create the content_file_name function to compute the path of the file path to save to return it.
And then we create the file FileField in the Content model by setting the upload_to argument to the content_file_name function so that it’s run at runtime to determine the upload path.