1

In this model, I want to change the name of the file uploaded in ImageField

class Product(models.Model):
    image = models.ImageField(upload_to=content_file_name)
    name = models.CharField(max_length=100)
    amount = models.PositiveIntegerField()

    class Meta:
        ordering = ('name',)

    def __str__(self):
        return self.name

To change the name of image I'm using this function

def content_file_name(instance, filename):
    ext = filename.split('.')[-1]
    filename = '%s.%s' % (instance.id, ext)

    return os.path.join('products', filename)

but the name of my image is None, if I use other fields like 'name', it works. What should I do to change the name with id? Thanks!

Jose Angel
  • 328
  • 2
  • 16

1 Answers1

7

The instance's id is not yet created, because the upload_to function is called before the new object is first written to the database.

In most cases, this object will not have been saved to the database yet, so if it uses the default AutoField, it might not yet have a value for its primary key field.

Emphasis from the Django docs

Two alternatives:

Use a uuid.uuid4() value, its easy to create and as unique as the pk.

Another suggestion, if you care about search engines and SEO, use a slugify(instance.name) so that your images can be easier found in the image search of search engines.

C14L
  • 12,153
  • 4
  • 39
  • 52