更新时间:2023-02-23 21:00:14
我经过大量搜索和发现此旧文档票证有很好的解释。
I figured it out after a lot of searching and finding this old documentation ticket that has a good explanation.
class UploadModel(models.Model):
image = models.ImageField(upload_to='uploads')
def save(self, *args, **kwargs):
# Call standard save
super(UploadModel, self).save(*args, **kwargs)
if 'uploads' in self.image.path:
initial_path = self.image.path
# New path in the form eg '/images/uploadmodel/1/image.jpg'
new_name = '/'.join(['images', self._meta.model_name, str(self.id),
path.basename(initial_path)])
new_path = os.path.join(settings.MEDIA_ROOT, 'images',
self._meta.model_name, self.pk, os.path.basename(initial_path))
# Create dir if necessary and move file
if not os.path.exists(os.path.dirname(new_path)):
makedirs(os.path.dirname(new_path))
os.rename(initial_path, new_path)
# Update the image_file field
self.image_file.name = new_name
# Save changes
super(UploadModel, self).save(*args, **kwargs)
现在我读了为此的文档,它看起来很明显:)但我确实认为可以使说明更具描述性。希望这可以节省一些时间!
Now I read the docs for this it looks totally obvious :) but I do think the explanation could be made more descriptive. Hopefully this will save someone some time!