Django - Tutorial 041. Display images in the admin panel on the example of a user profile

Image, Django, avatar

To improve the ability to display information about users in the administrative panel of the site, implemented the ability to display user avatars, both in the special UserProfile model that has One-To-One relationship to the User model, and in the User model itself, it added an avatar display via inline form.

It looks like this:

List of user profiles

List of user profiles

Displaying avatars in user profile

Avatar in user profile

a list of users

a list of users

Avatar in displaying user information

Avatar in displaying user information

Implementation

UserProfile model

models.py

# method for indicating where to load avatars
def upload_to(instance, filename):
    return 'avatars/%s' % filename


class UserProfile(LikeDislikeRelationMixin, models.Model):

    # We indicate the relationship to the user model
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    avatar = models.ImageField(
        verbose_name=_('Avatar'), upload_to=upload_to, null=True, blank=True
    )

    def __str__(self):
        return self.user.username

    # Here I return the avatar or picture with an owl, if the avatar is not selected
    def get_avatar(self):
        if not self.avatar:
            return '/static/images/owl-gray.svg'
        return self.avatar.url

    # method to create a fake table field in read only mode
    def avatar_tag(self):
        return mark_safe('<img src="%s" width="50" height="50" />' % self.get_avatar())

    avatar_tag.short_description = 'Avatar'

admin.py

Now let's see how to declare the administrative form for our UserProfile model.

class UserProfileAdmin(admin.ModelAdmin):
    list_display = ('avatar_tag', 'user') # As a field, specify the method that will return the picture tag in the list of user profiles.
    readonly_fields = ['avatar_tag'] # Be sure to read only mode
    fields = ('avatar_tag', 'user') # Specify the fields that need to be displayed in the administrative form

Модель User

With the user model will be a little easier. There is less information here.

admin.py

# Need inline form
class ProfileInline(admin.StackedInline):
    model = models.UserProfile # specify the profile model
    can_delete = False # prohibit removal
    fields = ('avatar_tag',) # Specify which field to display, again avatar tag
    readonly_fields = ['avatar_tag'] # Specify that this read only field

# Create your own form to display a user profile
class EUserAdmin(UserAdmin):
    # Specify what will be in the form of inline
    inlines = [
        ProfileInline 
    ]
    # modify the list of displayed fields to see the avatar with the other fields
    list_display = ('avatar_tag',) + UserAdmin.list_display

    # and also create a method for getting the avatar tag from the user profile
    def avatar_tag(self, obj):
        return obj.userprofile.avatar_tag()

Register all models in the administrative panel

admin.site.register(UserProfile, UserProfileAdmin)

admin.site.unregister(User)
admin.site.register(User, EUserAdmin)

For sites on Django recommend VDS-hosting TIMEWEB

Virtual hosting with 10 percent discount
Virtual hosting with 10 percent discount
EVILEG offers reliable hosting with a 10% discount for virtual hosting and 5% for VPS
Support the author Donate

Comments

Only authorized users can post comments.
Please, Log in or Sign up
NM
July 20, 2019, 10:59 a.m.
Nikolaj Morozov

C++ - Test 001. The first program and data types

  • Result:73points,
  • Rating points1
AD
July 19, 2019, 9:51 a.m.
Anastasia Dutchina

C++ - Test 001. The first program and data types

  • Result:53points,
  • Rating points-4
AD
July 19, 2019, 9:46 a.m.
Anastasia Dutchina

Qt - Test 001. Signals and slots

  • Result:57points,
  • Rating points-2
Last comments
July 21, 2019, 6:03 a.m.
Evgenij Legotskoj

да, наверное, 32-х разрядную поддержку уже давно поа было выкинуть. К слову, у вас много проектов под Android? Часто много где вижу вопросы о том, пишет ли кто-то вообще на Qt под мобильные си...
July 20, 2019, 2:41 p.m.
Andrej Jankovich

Очень полезная информация, увы уже выкинул поддержку 32 битных бедняг.
July 20, 2019, 9:31 a.m.
Mihailll

Вот так qDebug()<<"position:"<<event->scenePos();
July 20, 2019, 8:49 a.m.
Mihailll

Добрый день. Как можно узнать координату на графической сцене при отпускании клавиши мыши?
Now discuss on the forum
July 21, 2019, 6:07 a.m.
Evgenij Legotskoj

Если вы про этот метод QRectF MoveItem::boundingRect() const{ return QRectF (-30,-30,60,60);} То мне нужно было, чтобы координата (0,0) была по центру квадрата в его локальной си...
July 20, 2019, 11:04 a.m.
Mihailll

Так и с ресурсами работает QImage image(":/Images/Images/1.png");
July 19, 2019, 10:55 a.m.
Mihailll

Да. Там похоже каждое устройство генерирует свой токен, этот токен нужно как то получать и использовать в запросе. Но как это делать я пока не понял.
July 19, 2019, 9:31 a.m.
Mihailll

Добрый день. Повернул ListView в горизонтальное положение. При прокрутке эллементы выстраиваются у левого края окна. Как в QMK в ListView сделать центрирование по центру? ...
b
July 18, 2019, 2:27 a.m.
bbb116

Когда отрисовки не видно, объекты AreaSelector создаются (при нажатии и движении мышкой), но почему то не срабатывает paint() у них, хотя делаю update этой области. Причем эти области мо...
Looking for a Job?
5,000.00 руб. - 15,000.00 руб.
Дизайнер
Moskovskiy, Moscow, Russia
25,000.00 руб. - 30,000.00 руб.
Разработчик Qt/C++
Barnaul, Altai Krai, Russia

For registered users on the site there is a minimum amount of advertising

EVILEG
About
Services
Join us
© EVILEG 2015-2019
Recommend hosting TIMEWEB