使用Django将上传文件重命名为admin

使用Django将上传文件重命名为admin

本文介绍了使用Django将上传文件重命名为admin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当通过admin上传文件时,我在Django 1.6中使用了一个函数来重命名我的文件,但这在Django 1.8中不起作用.有人知道在1.8中是否仍有可能吗?

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'))

推荐答案

也许您需要使用 fileField 更改文件上传的方式.这是您的链接.

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

调用函数 upload_file 时,可以在此函数中重命名文件.

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

这篇关于使用Django将上传文件重命名为admin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 00:24