Last active
September 19, 2022 10:17
-
-
Save reganto/3d390e64ac8ef1d0a43f8339fe4d7908 to your computer and use it in GitHub Desktop.
Show image as thumbnail in Django admin change list (list view) and change form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Django 3.2.15 LTS | |
# Project structure | |
# | |
# project/ | |
# config/ | |
# __init__.py | |
# settings.py | |
# urls.py | |
# asgi.py | |
# wsgi.py | |
# core/ | |
# __init__.py | |
# admin.py | |
# apps.py | |
# models.py | |
# tests.py | |
# urls.py | |
# views.py | |
# templates/ | |
# core/ | |
# my_widget.html | |
# migrations/ | |
# manage.py | |
################ | |
# core/models.py | |
################ | |
class Profile(models.Model): | |
email = models.EmailField() | |
avatar = models.ImageField(upload_to="media") | |
#################### | |
# config/settings.py | |
#################### | |
MEDIA_URL = "/media/" | |
MEDIA_ROOT = BASE_DIR | |
################ | |
# config/urls.py | |
################ | |
from django.conf import settings | |
from django.conf.urls.static import static | |
if settings.DEBUG: | |
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) | |
############### | |
# core/admin.py | |
############### | |
@admin.register(Profile) | |
class ProfileAdmin(admin.ModelAdmin): | |
# Show image in change list (list view) | |
list_display = ("email", "show_avatar") | |
# Show image in add/change form as a readonly field | |
readonly_fields = ("show_avatar",) | |
# Customize image upload widget to show uploaded image as a thumbnail | |
def get_form(self, request, obj=None, **kwargs): | |
form = super().get_form(request, obj, **kwargs) | |
form.base_fields["avatar"].widget.template_name = "core/my_widget.html" | |
return form | |
# Calculated field | |
def show_avatar(self, obj): | |
from django.utils.html import format_html | |
return format_html('<img width=70 height=70 src="{}" />', obj.avatar.url) | |
# Column name | |
show_avatar.short_description = "Thumbnail" | |
#################################### | |
# core/templates/core/my_widget.html | |
#################################### | |
<p class="file-upload"> | |
Currently: | |
<img width=70 height=70 src="/media/{{ widget.value }}" /> | |
<br> | |
Change: | |
<input type="file" name="avatar" accept="image/*" id="id_avatar"> | |
</p> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment