Evgenii Legotckoi
Dec. 17, 2018, 11:51 p.m.

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

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

  1. # method for indicating where to load avatars
  2. def upload_to(instance, filename):
  3. return 'avatars/%s' % filename
  4.  
  5.  
  6. class UserProfile(LikeDislikeRelationMixin, models.Model):
  7.  
  8. # We indicate the relationship to the user model
  9. user = models.OneToOneField(User, on_delete=models.CASCADE)
  10.  
  11. avatar = models.ImageField(
  12. verbose_name=_('Avatar'), upload_to=upload_to, null=True, blank=True
  13. )
  14.  
  15. def __str__(self):
  16. return self.user.username
  17.  
  18. # Here I return the avatar or picture with an owl, if the avatar is not selected
  19. def get_avatar(self):
  20. if not self.avatar:
  21. return '/static/images/owl-gray.svg'
  22. return self.avatar.url
  23.  
  24. # method to create a fake table field in read only mode
  25. def avatar_tag(self):
  26. return mark_safe('<img src="%s" width="50" height="50" />' % self.get_avatar())
  27.  
  28. avatar_tag.short_description = 'Avatar'

admin.py

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

  1. class UserProfileAdmin(admin.ModelAdmin):
  2. list_display = ('avatar_tag', 'user') # As a field, specify the method that will return the picture tag in the list of user profiles.
  3. readonly_fields = ['avatar_tag'] # Be sure to read only mode
  4. 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

  1. # Need inline form
  2. class ProfileInline(admin.StackedInline):
  3. model = models.UserProfile # specify the profile model
  4. can_delete = False # prohibit removal
  5. fields = ('avatar_tag',) # Specify which field to display, again avatar tag
  6. readonly_fields = ['avatar_tag'] # Specify that this read only field
  7.  
  8. # Create your own form to display a user profile
  9. class EUserAdmin(UserAdmin):
  10. # Specify what will be in the form of inline
  11. inlines = [
  12. ProfileInline
  13. ]
  14. # modify the list of displayed fields to see the avatar with the other fields
  15. list_display = ('avatar_tag',) + UserAdmin.list_display
  16.  
  17. # and also create a method for getting the avatar tag from the user profile
  18. def avatar_tag(self, obj):
  19. return obj.userprofile.avatar_tag()

Register all models in the administrative panel

  1. admin.site.register(UserProfile, UserProfileAdmin)
  2.  
  3. admin.site.unregister(User)
  4. admin.site.register(User, EUserAdmin)

For sites on Django recommend VDS-hosting TIMEWEB

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    April 16, 2025, 5:08 p.m.
    Благодарю за отзыв. И вам желаю всяческих успехов!
  • IscanderChe
    April 12, 2025, 5:12 p.m.
    Добрый день. Спасибо Вам за этот проект и отдельно за ответы на форуме, которые мне очень помогли в некоммерческих пет-проектах. Профессиональным программистом я так и не стал, но узнал мно…
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…