Django:使用类字段的字符串格式

2024-09-28 03:22:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我想上传照片到不同的目录。目录名应该有一个来自模型类字段的标题。我试过了:

image = models.ImageField(upload_to=f"image/posts/{title}")

它创造了这个:

{1美元^

我想看看我得到<django.db.models.fields.CharField>的帖子标题。在

如何从该字段获取文本。为了设置文本,我使用了Django管理面板。在

模型.py

^{pr2}$

澄清:在我的图像字段中,我设置了上传地址。每个邮件的地址都不一样。每个帖子一个目录。目录名应该是title字段的值。在


Tags: to模型image文本目录标题titlemodels
1条回答
网友
1楼 · 发布于 2024-09-28 03:22:34

为了获得要上载图像的Post实例的title的值,upload_to必须是callable。该callable将接收实例作为参数,然后您可以获得标题。在

像这样:

def post_image_path(instance, filename):
    title = instance.title
    return f"image/posts/{title}/{filename}"

class Post(models.Model):
    # ...
    title = models.CharField(max_length=250)
    image = models.ImageField(upload_to=post_image_path)

相关问题 更多 >

    热门问题