首页 > 解决方案 > django - 陷入路径生成问题

问题描述

功能:

def custom_path(path):
    new_path = os.path.abspath(path)
    def get_path():
        return new_path
    return get_path

问题在于custom_path,当在此get_image_path函数中调用时,它会创建一个具有绝对路径的目录,例如<function custom_path at 0x7f432d99e158>/somedir/finalName.*ext,但我希望它以字符串表示形式返回。我的代码:

def get_image_path(instance, file):
    '''
    saves file to some location
    '''
    file_path   = custom_path*
    new_file    = random.randint(1, 45360789120)
    name, ext   = get_file_ext(file)
    ranstr      = random_string_generator(size=4)
    final_      = f'{ranstr}_{new_file}{ext}'
    return f'{file_path}/{new_file}/{final_}'

发件人:

from ... import custom_path, get_image_path

custom_path('posts')

class Post(models.Model):
    ...
    ...
    image   = models.FileField(upload_to=get_image_path, null=True,
              blank=True, verbose_name='article image (optional)')
    ...
    ...

否则,我必须将此功能修改为...

def get_image_path(instance, file):
    ...
    ...
    return f'posts*/{new_file}/{final_}' # and so on for *different models..

我也尝试过这样的事情......

def get_image_path(instance, file):
    ...
    ...
    return f'{new_file}/{final_}'

base = os.path.dirname('posts/')
upload_path = base + os.path.join(str(get_image_path))

class Post(models.Model):
    ...
    ...
    image   = models.FileField(upload_to=upload_path, null=True,
              blank=True, verbose_name='article image (optional)')
    ...
    ...

输出:''/newDir/newFile.*ext,如何摆脱它?️️

标签: pythondjangopython-3.x

解决方案


该函数custom_path返回内部函数get_path,因此它的工作方式如下:

foo = custom_path()  # foo is a function
path = foo()  # path is str now

或者,更短的代码:

path = custom_path()()

这是我的测试:

>>> import os
>>> def custom_path(path):
...   new_path = os.path.abspath(path)
...   def get_path():
...     return new_path
...   return get_path
... 
>>> foo = custom_path('test')
>>> foo
<function custom_path.<locals>.get_path at 0x7f7c123f8620>
>>> path = foo()
>>> path
'/home/pashawnn/test'

在您的情况下,您必须在 f-string 中添加大括号:

return f'{file_path()}/{new_file}/{final_}'

推荐阅读