如何将函数中的年月日和日期传递给创建的相关目录?

Bas*_*nda 2 python django

我有一个模型:

def author_document_path(instance, filename):
    return f"documents/{ instance.author.username }/%y/%m/%d/{filename}"


def author_blog_images(instance, filename):
    return f"blog-images/{instance.author.username}/%y/%m/%d/{filename}"

class Blog(models.Model):
    title = models.CharField(max_length=255)
    # other fields
    thumbnail = models.ImageField(upload_to=author_blog_images)
    documents = models.FileField(upload_to=author_document_path)
Run Code Online (Sandbox Code Playgroud)

传递f"blog-images/{instance.author.username}/%y/%m/%d/{filename}"上述两个函数的正确方法是什么,因为这些函数不会将Year文件夹创建为2019,month文件夹创建为5,day文件夹创建为30。在上载受尊重的文件和图像之后,目录如下所示:

在此处输入图片说明

这不是我想要的,我希望它看起来像:

在此处输入图片说明

你能帮我吗 非常感谢。

Wil*_*sem 6

你先取当天,然后你就可以得到yearmonth并且day属性,如:

from datetime import date

def author_blog_images(instance, filename):
    td = date.today()
    return f'blog-images/{instance.author.username}/{td.year}/{td.month}/{td.day}/{filename}'
Run Code Online (Sandbox Code Playgroud)

这里td.monthtd.day具有前导零(所以它会被打印为2019/5/30 )。但是,您可以在格式字符串中使用前导零,例如:2019/05/30

from datetime import date

def author_blog_images(instance, filename):
    td = date.today()
    return f'blog-images/{instance.author.username}/{td.year}/{td.month:02d}/{td.day:02d}/{filename}'
Run Code Online (Sandbox Code Playgroud)

或者我们可以使用特定的日期格式:

from datetime import date

def author_blog_images(instance, filename):
    td = date.today().strftime('%y/%b/%d')
    return f'blog-images/{instance.author.username}/{td}/{filename}'
Run Code Online (Sandbox Code Playgroud)

我们也可以使用@BearBrown所说的 Django的timezone.now[Django-doc]

from django.utils import timezone

def author_blog_images(instance, filename):
    td = timezone.now().strftime('%y/%b/%d')
    return f'blog-images/{instance.author.username}/{td}/{filename}'
Run Code Online (Sandbox Code Playgroud)

我们甚至可以将f字符串作为参数传递给strftime,就像@chepner所说的那样,替换之前的某些部分,然后将strftimeformat time替换为f字符串产生的格式字符串:

from django.utils import timezone

def author_blog_images(instance, filename):
    return timezone.now().strftime(f'blog-images/{instance.author.username}/%y/%b/%d/{filename}')
Run Code Online (Sandbox Code Playgroud)

但是,这里需要考虑一个极端的情况:如果instance.author.usernamefilename包含诸如%d和的格式部分%b,则strftime将会分别用day / month / ...替换它们。尽管这不是很常见,但还是要考虑到这一点。

您还应该考虑的另一件事是,在author更改或其名称时username,文件将不会重命名,因此它仍将保留旧作者的名称(或该作者的旧用户名)。