Python 如何将函数中的年、月和日期传递给已创建的相关目录?
我有一个模型:Python 如何将函数中的年、月和日期传递给已创建的相关目录?,python,django,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}" cla
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)
在上述两个函数中传递f“blog images/{instance.author.username}/%y/%m/%d/{filename}”
的正确方法是什么,因为这些函数不创建2019年的年文件夹、5年的月文件夹和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}/{td.day}/{filename}'
或者我们可以使用特定的日期格式:
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}'
我们甚至可以将一个f字符串作为参数赋给strftime
,比如替换前面的某些部分,然后让strftime
用f字符串生成的格式字符串格式化time
:
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}')
从django.utils导入时区
def author_blog_图像(实例,文件名):
return timezone.now().strftime(f'blog-images/{instance.author.username}/%y/%b/%d/{filename}')
但是,这里应该考虑一个边缘情况:如果实例.author.username
或文件名
包含格式部分,如%d
和%b
,则strftime
将用天/月/替换它们。。。分别地虽然这种情况并不常见,但也需要加以考虑
您应该考虑的另一件事是,当
作者
或其用户名
发生更改时,该文件将不会重命名,因此它仍然保留旧作者的名称(或该作者的旧用户名).也许更好的django.utils.timezone?请注意,strftime
可以创建整个路径:date.today().strftime(f'blog-images/{instance.author.username}/%y/%b/%d/{filename}')
@chepner:我认为有一个可能的问题:如果usename
或filename
包含%d
。我同意这不是很常见,我会把它添加到答案中,但我认为在有限的情况下,它可能会失败。啊,好的观点<代码>strftime应限制为固定字符串。
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}'
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}')