如何将用户个人资料的头像图像渲染到ag模板中? [英] How to render the user profile avatar image into the wagtail template?

查看:48
本文介绍了如何将用户个人资料的头像图像渲染到ag模板中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Wagtail CMS创建一个博客网站.每当发布新帖子时,我都想显示作者头像图像.我正在尝试从此/admin/account/change_avatar/位置渲染图像.我可以看到此处上传的图片在 wagtailusers_userprofile->下列名:头像表,但不确定如何在模板中呈现它.

I am creating a blog site using the Wagtail CMS. I would like to display the Author avatar image whenever a new post is published. I am trying to render the image from this /admin/account/change_avatar/ location. I can see the image uploaded here is under the wagtailusers_userprofile -> col name: avatar table, but not sure how to render it in the template.

推荐答案

此图像不是典型的Wagtail图像(一个来自 wagtailimages.Image 的图像),看起来像是常规的 models.ImageField .

This image isn't a typical Wagtail Image (one that comes from wagtailimages.Image), this looks like a regular models.ImageField.

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

Here's what's in the UserProfile model for the avatar:

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.

Because this is a regular image field, you can get the url by appending .url in your template.

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

Here's some example template code:

{% 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 %}

上面的代码将检查用户是否在模板中通过了身份验证.如果不需要,则将其沟渠.

The above code will check to see if the user is authenticated in the template. If you don't need it, ditch it.

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

THen there's the if statement to checks of the request.user.wagtail_userprofile.avatar exists. The wagtail_userprofile comes from the user field on the UserProfile model. It's using a related_name, so we use that in the template.

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

I also sprinkled in a {{ request.user.get_full_name }} for the alt tag, because the image alt should probably be the users name in this case, rather than the file name.

如果需要高度或宽度,都可以通过 {{request.user.wagtail_userprofile.avatar.height}} {{request.user.wagtail_userprofile.avatar.width}} .

If you need the height or width, those are both available through the {{ request.user.wagtail_userprofile.avatar.height }} and {{ request.user.wagtail_userprofile.avatar.width }}.

这篇关于如何将用户个人资料的头像图像渲染到ag模板中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆