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.
1 Answer
This image isn't a typical Wagtail Image (one that comes from wagtailimages.Image
), this looks like a regular models.ImageField
.
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,
)
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.
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.
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.
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 }}
.
-
4Thank you @Kalob Taulien for the solution. By the way, I learned wagtail by watching all your tutorials from the Coding For Everybody Youtube channel. Commented Mar 2, 2019 at 4:50
-
1How would this look when a gravatar is used? I found (from wagtail.users.utils import get_gravatar_url) Commented Oct 27, 2020 at 10:02