0

I have used a function in Django 1.6 to rename my files when they are uploaded through admin, but this does not work in Django 1.8. Anyone know if it is still possible to do this in 1.8?

class Entry(models.Model):

    def path_and_rename(path):
        def wrapper(instance, filename):
            ext = filename.split('.')[-1]
            # get filename
            if instance.pk:
                filename = "%s-%s.%s" % (instance.pub_date.year,instance.issue, ext)
            else:
                # set filename as random strin
                filename = "%s.%s" % (uuid.uuid4(), ext)    
            # return the whole path to the file
            return os.path.join(path, filename)
        return wrapper


    name = models.CharField(max_length=500)
    pub_date = models.DateTimeField()
    issue = models.PositiveIntegerField()  

    pdf = models.FileField(blank=True, upload_to=path_and_rename('uploads/pdf'))
jww
  • 97,681
  • 90
  • 411
  • 885
Tomas Jacobsen
  • 2,368
  • 6
  • 37
  • 81
  • Possible duplicate of [How to change the file name of an uploaded file in Django?](https://stackoverflow.com/q/2680391/608639), [Choose the filename of an uploaded file with Django](https://stackoverflow.com/q/1237602/608639), [Django File Upload and Rename](https://stackoverflow.com/q/25652809/608639), [Rename file on upload to admin using Django](https://stackoverflow.com/q/30167409/608639), etc. – jww Sep 21 '18 at 09:22

1 Answers1

0

Maybe you need to change the way file uploaded by using the fileField. Here is link for you.

When function upload_file gets called, you can rename the file in this function.

Stephen Lin
  • 4,852
  • 1
  • 13
  • 26