Opened 15 years ago

Closed 14 years ago

#12009 closed (wontfix)

Allow name of file in FileField/ImageField to be based on primary key

Reported by: krzyk Owned by: nobody
Component: File uploads/storage Version: 1.1
Severity: Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Currently there is no way to prevent admin from uploading file with the same name (which will result in overwriting the previous file) (having zillions of date based directiories is not a good idea).
The simplest solution would be to use primary key as the file name, but when upload_to callable is called the instance doesn't have the primary key yet.

class Gallery(models.Model):
    name = models.CharField(max_length=255)

def image_upload(instance, filename):
        return 'content/gallery/' + gallery.id + '/' + instance.id + '.jpg' # extension can be retrieved from filename

class Image(models.Model):
    gallery = models.ForeignKey(Gallery)
    title = models.CharField(max_length=255)
    image = models.ImageField(upload_to=image_upload)

The above results in creation of None.jpg file.

Change History (1)

comment:1 by Russell Keith-Magee, 14 years ago

Resolution: wontfix
Status: newclosed

I won't disagree that it would be *nice* to be able to do this, but it's also a logical impossibility. In order for an object to have a primary key, it must have been saved. If a model has a non-null FileField, that field must have a value in order for the instance to be saved. Therefore, the file field must be able to generate a filename for an instance that hasn't been saved yet. This precludes the use of the primary key.

Unless you can propose a technique for doing this (that doesn't involve double saving of the instance), I'm closing wontfix.

Note: See TracTickets for help on using tickets.
Back to Top