B
B
bimka2022-01-21 17:58:21
Django
bimka, 2022-01-21 17:58:21

Why does the admin panel not show user avatars?

In the admin panel, you need to display the user's avatar, but it doesn't work for me. I already tried to specify the absolute address of the avatar, but it does not show it either:
61eac929289b2614102456.png

models.py:

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.core.validators import MinLengthValidator
from django.utils.safestring import mark_safe

from .managers import CustomUserManager

class Client(AbstractUser):    
    avatar = models.ImageField(upload_to = "static/images/", verbose_name="Аватарка")
    gender = models.CharField(
        max_length = 10,
        verbose_name="Пол",
        choices = (('male', 'Кот'), ('female', 'Кошка')),
        default = 'male')
    first_name = models.CharField(
        verbose_name="Имя",
        max_length = 30, 
        validators=[MinLengthValidator(2, "Имя не менее 2 символов!")])
    last_name = models.CharField(
        verbose_name="Фамилия",
        max_length = 30, 
        validators=[MinLengthValidator(2, "Фамилия не менее 2 символов!")])
    email = models.EmailField(verbose_name="Email", unique=True)    
    username = None
    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = []    
    objects = CustomUserManager()

    def __str__(self):
        return f"{self.first_name} {self.last_name}, {self.gender}"


admin.py:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.safestring import mark_safe

from .models import Client
from .form import ClientCreateForm, ClientChangeForm

class CustomUserAdmin(UserAdmin):
    add_form = ClientCreateForm
    form = ClientChangeForm
    model = Client
    Client
    
    #readonly_fields = ['avatar_tag',]
    list_display = ('email', 'is_staff', 'is_active', 'first_name', 'last_name', 'get_avatar', 
            'avatar', 'gender')
    list_filter = ('email', 'is_staff', 'is_active', )
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Permissions', {'fields': ('is_staff', 'is_active', 'first_name', 'last_name',  'avatar_tag', 
            'avatar', 'gender')}),
    )
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('first_name', 'last_name',  'avatar_tag', 
            'avatar', 'gender','is_staff', 'is_active',              
            'email', 'password1', 'password2',)}
        ),
    )
    search_fields = ('email',)
    ordering = ('email',)

    def get_avatar(self, obj):
        #return mark_safe(f'<img src="{obj.avatar.url}" width="100"/>')
        return mark_safe(f'<img src="static/images/2.jpg" width="100"/>')

admin.site.register(Client, CustomUserAdmin)


at
def get_avatar(self, obj):
     return mark_safe(f'<img src="{obj.avatar.url}" width="100"/>')


throws an error:
ValueError at /admin/api/client/
The 'avatar' attribute has no file associated with it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Nesterov, 2022-01-21
@AlexNest

Because not all users have an avatar, and it is not specified by default.

def get_us_avatar(self, obj):
        print(repr(obj.avatar))
        if obj.avatar:
            return mark_safe(f'<img src="{obj.avatar.url}" alt="" height="100px">')
        else:
            return mark_safe(f'<img src="" alt="">')

PS To store user files, you should use the media folder.
And yes - use a random name generator, otherwise at some point the user will upload a picture whose name matches the name of the one already uploaded.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question