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

Image, Django, avatar

Content

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

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
Support the author Donate

Comments

Only authorized users can post comments.
Please, Log in or Sign up
How to become an author?

Contribute to the evolution of the EVILEG community.

Learn how to become a site author.

Learn it
Donate

Good day, Dear Users!!!

I am Evgenii Legotckoi, developer of EVILEG. And it is my hobby project, which helps to learn programming another programmers and developers

If the site helped you, and you want also support the development of the site, than you can donate by following ways

PayPalYandex.Money
Timeweb

Let me recommend you the excellent hosting on which EVILEG is located.

For many years, Timeweb has been proving his stability.

For projects on Django I recommend VDS hosting

View Hosting Timeweb
MN
May 25, 2020, 11:33 a.m.
Mitja Nagibin

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
f
May 25, 2020, 5:05 a.m.
falcon

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

  • Result:66points,
  • Rating points-1
jm
May 25, 2020, 3:30 a.m.
just maks

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
Last comments
May 26, 2020, 6:51 a.m.
Evgenij Legotskoj

Qt/C++ - Lesson 004. QSqlTableModel – How to present the table from database?

У вас база данных не открылась Исправьте путь к базе данных на свой корректный в следующих методах void DataBase::connectToDataBase() bool DataBase::openDataBase()
T1
T1
May 26, 2020, 6:22 a.m.
Tima 1

Qt/C++ - Lesson 004. QSqlTableModel – How to present the table from database?

полностью повторил структору проекта. В форму дабавил tableView. Но при запуске получаю форму только с пустым tableView. Можете подсказать в чем пробелма?
May 26, 2020, 6:02 a.m.
Evgenij Legotskoj

Qt/C++ - Lesson 004. QSqlTableModel – How to present the table from database?

Потому что это файл который нужно создать, а не библиотека. В статье есть содержание этого файла. Добавляйте в проект. Копируйте содержимое из статьи.
T1
May 26, 2020, 6 a.m.
Tima 1

Qt/C++ - Lesson 004. QSqlTableModel – How to present the table from database?

не удается подключиить библеотеку include "database.h" выдает ошибку. Можете помочь?
Now discuss on the forum
May 26, 2020, 5:16 a.m.
BlinCT

Отсутствие драйвера SQLite в пакете Qt 4 на Linux

Вот честно непонимаю почему до сих пор используют qt4, там же столько всего отсутствует, много фишек и возможностей нету там. То есть используя такое старье приходится много писать самому а не и…
DK
May 26, 2020, 2:24 a.m.
Dzhon Kofi

Disable autoscroll

такие естественные решения все перепробовал. Получилось вчера так: const int maximumScroll = ui->_samples->verticalScrollBar()->maximum();const int sliderPos = ui->_samp…
May 26, 2020, 12:43 a.m.
Ruslan Polupan

Посоветуйте новичку (базы данных и Qt, что учить)

Без БД сейчас практически никуда. Поэтому SQL надо знать. SQLite самы простой вариант, но имхо лучще начать с бд клиент-сервер. Настроить сервер. Подключаться клиентом. Просто это помогает понят…
EJ
May 25, 2020, 2:42 p.m.
Esteban José María

Компиляция пустого проекта Qt Android

qt 5.12.8 BUILD SUCCESSFUL in 42s 28 actionable tasks: 28 executed Android package built successfully in 68.251 ms. Ну, буду разбираться по-тихоньку. :)
s
May 25, 2020, 1:24 p.m.
sander-007

Использование файлов в памяти (memory file mapping)

Добрый вечер, проблемы работы с файлом Exel нет вообще. Весь смысл в том чтобы не создавать на диске физический файл (требования безопасности), дабы потом не чистить. А так вопрос только в этом …
About
Services
© EVILEG 2015-2020
Recommend hosting TIMEWEB