简体   繁体   English

在django model.py中添加了Image字段,上载时其默认名称如何

[英]Added Image field in django model.py , how ever when uploading it takes default name

my model.py as follows, 我的model.py如下,

 class Employee(models.Model):
    id = models.IntegerField(max_length = 6,primary_key=True,verbose_name="Employee ID")
    name = models.CharField(max_length = 100,verbose_name="Name")
    image = models.ImageField(upload_to = ".",blank=True,null=True)

When i try to add image in django admin, it uploads the image to /site_media/media. 当我尝试在django admin中添加图像时,它将图像上传到/ site_media / media。 Here i want to replace the uploaded image name with my primary key field ID.jpeg, so that i can retrieve and show that in html pages . 在这里,我想用主键字段ID.jpeg替换上载的图像名称,以便我可以在html页面中检索和显示该图像。

Even now i can retrieve the image name because its stored in db. 即使现在我也可以检索图像名称,因为它存储在数据库中。 However for simplifying i need to customize the image name before upload. 但是为了简化,我需要在上传之前自定义图像名称。 Also if the user uploads another image for same person it should overwrite the old one. 同样,如果用户为同一个人上传另一张图片,则它应覆盖旧图片。 At present it just changes the new name in db. 目前,它只是更改db中的新名称。 But still old image is present in the media folder 但是媒体文件夹中仍然存在旧图像

You can use a function for upload_to ; 您可以将函数用于upload_to ;

def sample_upload_to_function(instance, filename):
    extension = filename.split('.')[-1]
    return "%s.%s" %(instance.id, extension)

class Employee(models.Model):
    .....
    image = models.ImageField(upload_to =sample_upload_to_function, blank=True, null=True)

But i don't know how to overwrite existing file. 但是我不知道如何覆盖现有文件。 I think before save, you must delete the existing file. 我认为在保存之前,必须删除现有文件。

You can use a callable for upload_to as follows: 您可以按如下方式将可调用对象用于upload_to

def file(self, filename):
    url = "./%d.JPG" % (self.id,)
    return url

class Employee(models.Model):
    id = models.IntegerField(max_length = 6,primary_key=True,verbose_name="Employee ID")
    name = models.CharField(max_length = 100,verbose_name="Name")
    image = models.ImageField(upload_to = file,blank=True,null=True)

But you will face the problem of Django not overwriting the file which can be solved by a custom storage or deleting the file. 但是您将面临Django无法覆盖文件的问题,这可以通过自定义存储或删除文件来解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM