如何将用户个人资料头像图像渲染到 wagtail 模板中?

How to render the user profile avatar image into the wagtail template?

我正在使用 Wagtail CMS 创建博客站点。我想在发布新 post 时显示作者头像图像。我正在尝试从这个 /admin/account/change_avatar/ 位置渲染图像。我可以看到这里上传的图片在 wagtailusers_userprofile -> col name: avatar table 下,但不确定如何在模板中渲染它。

这张图片不是典型的鹡鸰图片(来自 wagtailimages.Image),这看起来像一张普通的 models.ImageField

以下是头像的 UserProfile 模型中的内容:

class UserProfile(models.Model):

    user = models.OneToOneField(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='wagtail_userprofile'
    )

    avatar = models.ImageField(
        verbose_name=_('profile picture'),
        upload_to=upload_avatar_to,
        blank=True,
    )

因为这是一个常规图像字段,您可以通过在模板中附加 .url 来获得 url。

下面是一些示例模板代码:

{% if request.user.is_authenticated %}
  {% if request.user.wagtail_userprofile.avatar %}
    <img src="{{ request.user.wagtail_userprofile.avatar.url }}" alt="{{ request.user.get_full_name }}">
  {% else %}
    {# No image #}
  {% endif %}
{% endif %}

以上代码将检查用户是否在模板中进行了身份验证。如果你不需要它,就把它扔掉。

然后有 if 语句来检查 request.user.wagtail_userprofile.avatar 是否存在。 wagtail_userprofile 来自 UserProfile 模型的 user 字段。它使用 related_name,所以我们在模板中使用它。

我还为 alt 标签添加了一个 {{ request.user.get_full_name }},因为在这种情况下图像 alt 可能应该是用户名,而不是文件名。

如果您需要高度或宽度,可通过 {{ request.user.wagtail_userprofile.avatar.height }}{{ request.user.wagtail_userprofile.avatar.width }} 获得。