0

I want to serialize the profile avatar from Wagtail admin with ImageRenditionField. Basing on the answer from the question I tried this:

# models.py
class User(AbstractUser):

    def get_avatar(self):
        return self.wagtail_userprofile.avatar


# serializers.py
class UserSerializer(serializers.ModelSerializer):

    avatar = ImageRenditionField('width-190', source='get_avatar')
    class Meta:
        model = User
        fields = ['id', 'username', 'first_name', 'last_name', 'avatar']

I got this:

Django Version: 3.1.4
Exception Type: AttributeError
Exception Value:    
'ImageFieldFile' object has no attribute 'get_rendition'

How do I throw user avatar into ImageRenditionField?

  • I checked source code of the userprofile, it is not inherited from the `AbstractImage` model, which means you won't have `get_rendition` available for this image. you can resize in your serializermethod though – minglyu Jan 01 '21 at 12:02

2 Answers2

0

you can do this

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = "__all__

class PersonSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)
    class Meta:
        model = Person
        fields = "__all__"
    avatar = serializers.SerializerMethodField("get_avatar_display")
    def get_avatar_display(self,info):
        return info.wagtail_userprofile.avatar.url
0

The avatar field is a regular Django ImageField. It does not have get_rendition, it does not have any Wagtail rendition logic.

Take a look at wagtail.users.models.UserProfile.avatar

class UserProfile(models.Model):
    ...

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

and wagtail.images.models.AbstractImage.file (this is the base class of Wagtail Image).

class AbstractImage(CollectionMember, index.Indexed, models.Model):
    ...
    file = models.ImageField(
        verbose_name=_('file'), upload_to=get_upload_to, width_field='width', height_field='height'
    )

Notice that avatar field is a regular Django ImageField. The Wagtail image is a model that stores additional image information and handles filters, focal points and renditions.

You can NOT use the Wagtail renditions in combination with avatar field, because avatar is a Django ImageField and not a Wagtail Image.

There are various thumbnail packages that provide thumbnail/scale functionality for Django ImageFields. Don't adjust the UserProfile.avatar field itself (customising Wagtail). Search for packages that play nice with plain ImageFields.

This question and answer might interest you.

allcaps
  • 10,945
  • 1
  • 33
  • 54