[英]How to save an image to a customized filepath in django admin?
I am trying to upload images to specific folders I select.我正在尝试将图像上传到我选择的特定文件夹。 the model code is as below:型号代码如下:
class PhotosTags(models.Model):
Tag_name = models.CharField('Tag Name', max_length=100, default='NA', unique=True)
Description = models.TextField('Tag Description', max_length=200, blank=True)
class Meta:
verbose_name = 'Tags'
verbose_name_plural = verbose_name
ordering = ['Date_created']
def __str__(self):
return str(self.Tag_name)
class Photos(models.Model):
Name = models.TextField('Photo Name', max_length=200, blank=True)
Tag = models.ForeignKey(PhotosTags, on_delete=models.CASCADE, default=None)
filepath = 'Gallery'
Photo = models.ImageField(upload_to=filepath, blank=False)
class Meta:
verbose_name = 'Photos'
verbose_name_plural = verbose_name
ordering = ['Date_uploaded']
pre_save.connect(upload_photo, sender=Photos)
Here each tag has its own folder.这里每个标签都有自己的文件夹。 The function I want to realize is, when I upload an image, I can select a specific tag (through selection of "Tag") and then this image can be uploaded to that folder.我想实现的功能是,当我上传图片时,我可以选择一个特定的标签(通过选择“标签”),然后可以将这张图片上传到该文件夹中。 I tried use: signals
to change the filepath
but failed.我尝试使用: signals
来更改文件filepath
但失败了。 The code i wrote is:我写的代码是:
def upload_photo(sender, instance, **kwargs):
tardir = instance.Tag.Tag_name
instance.filepath = 'Gallery'+'/'+tardir
You can achieve it by sending upload_to path with a function.您可以通过使用函数发送 upload_to 路径来实现它。
import os
def path_generator(instance, filename):
base, extension = os.path.splitext(os.path.basename(filename))
file_dir = f"your_desired_path.{extension}"
return file_dir
class Photos(models.Model):
Name = models.TextField('Photo Name', max_length=200, blank=True)
Tag = models.ForeignKey(PhotosTags, on_delete=models.CASCADE, default=None)
Photo = models.ImageField(upload_to=path_generator, blank=False)
class Meta:
verbose_name = 'Photos'
verbose_name_plural = verbose_name
ordering = ['Date_uploaded']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.