0

my model.py as follows,

 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. 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 .

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. But still old image is present in the media folder

Naggappan Ramukannan
  • 2,564
  • 9
  • 36
  • 59

2 Answers2

1

You can use a function for 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.

iskorum
  • 1,137
  • 1
  • 16
  • 27
1

You can use a callable for upload_to as follows:

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.

Community
  • 1
  • 1
arocks
  • 2,862
  • 1
  • 12
  • 20