Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 782
rameshrasaiyan Avatar asked Jan 27 '23 15:01

rameshrasaiyan


1 Answers

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 }}.

like image 179
Kalob Taulien Avatar answered May 15 '23 05:05

Kalob Taulien