UserProfile
is CustomUser Model having columns avatar, bio and display fields.
I want to show Profile avatar in the User List
I have added avatar_tag function to be called by the users list
#models.py
class UserProfile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
def get_upload_avatar_to(self, filename):
return f"images/avatar/{self.user.id}/{filename}"
avatar = models.ImageField(upload_to=get_upload_avatar_to, null=True, blank=True)
def avatar_tag(self):
if self.avatar.url is not None:
return mark_safe('<img src="{}" height="50"/>'.format(self.avatar.url))
else:
return ""
avatar_tag.short_description = 'Image'
avatar_tag.allow_tags = True
full_name = ''
bio = models.TextField(default="", blank=True)
display = models.CharField(default=full_name,max_length=512,blank=True)
admin.py code is below
class UserProfileInline(admin.StackedInline):
model = UserProfile
fk_name = 'user'
can_delete = False
verbose_name = "User profile"
verbose_name_plural = 'Profiles'
classes = ('text-capitalize','collapse open')
extra = 1
list_display = ('avatar_tag')
fieldsets = (
("Profile", {'fields': ('avatar','bio', 'display',)}),)
class UserProfileAdmin(UserAdmin):
inlines = (UserProfileInline,)
How can I show the avatar image in list view of the User table?
I am not getting any errors in the user list avatar is not shown
Try this code
from django.utils.html import format_html
class UserProfileAdmin(UserAdmin):
list_display = ("avatar_tag",) # pass other fileds if you want eg. name
def avatar_tag(self, obj):
if obj.userprofile.avatar:
return format_html(
'<img src="%s"/>' % obj.userprofile.avatar.url
)
return "No avatar"
list_display
accepts callable argument so you can pass custom method names in it.