Django通过“用户名”上传

时间:2019-02-23 09:34:10

标签: django django-rest-framework

我想按用户名上传文件。

class Beat(models.Model):
    title       = models.CharField(max_length=100, blank=True, default='')
    author      = models.CharField(max_length=100, blank=True, default='')
    owner       = models.ForeignKey(User, related_name='beats', on_delete=models.CASCADE, default='', blank=True, null=True)

    mbeat = models.FileField(upload_to='beat/', default = 'static/None/No-beat.mp3')

这是我的抽象代码。这段代码将文件上传到“ beat”文件夹。

但是,我想使存储的可视性更有效。我试图将作者姓名添加到upload_to参数中,如下所示:

upload_to='beat/%s/' %author

但这没成功。

如何解决此问题? 谢谢。

2 个答案:

答案 0 :(得分:1)

您可以按照

def user_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/beat/author/<filename>
    return 'beat/{0}/{1}'.format(instance.author, filename)

class Beat(models.Model):
    title       = models.CharField(max_length=100, blank=True, default='')
    author      = models.CharField(max_length=100, blank=True, default='')
    owner       = models.ForeignKey(User, related_name='beats', on_delete=models.CASCADE, 
    default='', blank=True, null=True)
    upload = models.FileField(upload_to=user_directory_path,  default = 'static/None/No-beat.mp3')

引用link

答案 1 :(得分:-1)

您可以将这样的函数传递给upload_to

mbeat = models.ImageField(upload_to=upload_to_path(path='beat'),
                              default = 'static/None/No-beat.mp3')

此函数必须返回partial

def upload_to_path(path):
    return partial(_get_upload_to_path, path=path)


def _get_upload_to_path(instance, filename, path):
    """

    :param instance: instance of the model
    :param filename: filename of the uploaded file
    :param path: path to the directory where to upload
    :return: complete path with filename
    """
    return os.path.join(path, instance.author, filename)

使用partial可以“冻结”函数的调用,始终传递部分调用中指示的参数,在这种情况下,此参数是odel中指定的路径。在运行时,该函数将接收从django传递的参数(该参数需要一个函数,该函数接受upload_to属性的实例和文件名)以及您在局部函数中指定的参数。由此您可以返回完整的路径