2

像 django 的 upload_to

def upload_to(instance, filename):
    filename = time.strftime('%Y%m%d%H%M%S')
    ym = time.strftime('%Y%m')
    return 'uploads/%s/%s.jpg' % (ym,filename)

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    photo = models.ImageField(u"Image (Upload)",upload_to=upload_to)

文件已保存“上传/%s/%s.jpg”

但改变为

photo = FileBrowseField("Image", max_length=200, directory="uploads/", extensions=[".jpg"], blank=True, null=True)

如何在将文件上传到 django 的 upload_to 之类的文件夹之前重命名文件

4

1 回答 1

1

In filebrowser/sites.py you can create a hook for this when uploading / handling uploads:

def _upload_file(self, request):
    """
    Upload file to the server.
    """
    if request.method == "POST":
        folder = request.GET.get('folder', '')

        if len(request.FILES) == 0:
            return HttpResponseBadRequest('Invalid request! No files included.')
        if len(request.FILES) > 1:
            return HttpResponseBadRequest('Invalid request! Multiple files included.')

        filedata = list(request.FILES.values())[0]

        fb_uploadurl_re = re.compile(r'^.*(%s)' % reverse("filebrowser:fb_upload", current_app=self.name))
        folder = fb_uploadurl_re.sub('', folder)

        path = os.path.join(self.directory, folder)
        # we convert the filename before uploading in order
        # to check for existing files/folders
        file_name = convert_filename(filedata.name)
        filedata.name = file_name
        file_path = os.path.join(path, file_name
        ....

You can modify file_path here to whatever you like, or modify the file name.

For those of you that just want to ensure that files are not overwritten, you can set the FILEBROWSER_OVERWRITE_EXISTING flag in your settings.py as such:

FILEBROWSER_OVERWRITE_EXISTING = False

This will ensure that when you edit your files you give them a unique name, and it also ensures new uploads get their filename converted to something unique using filebrowsers convert_filename method defined in filebrowser/utils.py

More on filebrowser settings here. Hope this helps :)

于 2014-11-11T18:41:28.477 回答