K
K
kvarel2022-01-04 12:30:40
Django
kvarel, 2022-01-04 12:30:40

DJANGO How to add images to Select from DB?

The task is to create a form in which there is a field for selecting one of the users. The drop-down list should display the user's avatar and name.

Created a model to extend the User model.

class UserInfo(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    avatar = models.ImageField(verbose_name='Аватар', upload_to='avatar/', blank=True)
    number = models.IntegerField(verbose_name='Номер телефона', unique=True, blank=True, null=True)
    mail = models.EmailField(verbose_name='Эл.почта', unique=True, blank=True)


So I'm trying to override the __str__ method on the User model
def edit_str_user(self):
    try:
        avatar = UserInfo.objects.get(user=self).avatar
        return f'<img src="{avatar.url}" height=50 align="left"> {self.first_name}'
    except:
        return f'{self.first_name}'

User.__str__ = edit_str_user


At the output I get
kG1VG3Zy.jpg?download=1&name=%D0%A1%D0%BA%D1%80%D0%B8%D0%BD%D1%88%D0%BE%D1%82%2004-01-2022%2012:27 :39.jpg

How to make it so that I see the picture, and not the path to it?
I think you need to somehow edit the widget, write something in attr, please help

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2022-01-04
@kvarel

The HTML select element doesn't do that. You need to look for some js library.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question