Per the documentation for FileField.upload_to
:
This may also be a callable, such as a function, which will be called to obtain the upload path, including the filename. This callable must be able to accept two arguments, and return a Unix-style path (with forward slashes) to be passed along to the storage system. The two arguments that will be passed are:
instance
: An instance of the model where the FileField is defined. More specifically, this is the particular instance where the current file is being attached. In most cases, this object will not have been saved to the database yet, so if it uses the default AutoField
, it might not yet have a value for its primary key field.
filename
: The filename that was originally given to the file. This may or may not be taken into account when determining the final destination path.
So if you've got a model which has a stock_number
attribute, you could use something like this:
def get_path(instance, filename):
return 'photos/%s/%s' % (instance.stock_number, filename)