Customize save path for ImageField
I want to customize the folders that are used to save my images for a record...currently, I have:
original_image = models.ImageField(upload_to='photos')
But what I want to have is the images being saved to photos/<v开发者_如何学编程ehicle's_stock_number>/
...how can I add the stock number to the end of the upload path?
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 defaultAutoField
, 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)
精彩评论