In Django 4.1 admin I'm having a problem: i can upload files but can't show it.
My environment is:
running the development server with: python manage.py runserver --insecure 0.0.0.0:8000
The project root is in C:\django\humm\humm
The project tree is:
- humm
- backend
...
admin.py
models.py
...
- humm
...
settings.py
urls.py
...
- media
- images
pd.png (successfully uploaded image)
urls.py:
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('', admin.site.urls),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
models.py:
...
class Produto(models.Model):
...
descricao = models.CharField(db_column='product_name', max_length=40)
imagem_pequena = models.ImageField(db_column='small_image', upload_to='images/', blank=True, null=True)
admin.py
...
class ProdutoAdmin(admin.ModelAdmin):
def thumb_pequeno(self, obj):
if obj.imagem_pequena:
return format_html('<img src="{}" style="max-width:100px; max-height:100px"/>', obj.imagem_pequena.url)
else:
return '-'
thumb_pequeno.short_description = 'pequena'
# i tried 'imagem_pequena.allow_tags = True, but this was deprecated in
# Django 4.11 in favor of format_html'
readonly_fields = [...,'thumb_pequeno',]
list_display = ['descricao','thumb_pequeno',]
...
admin.site.register(Produto, ProdutoAdmin)
settings.py:
...
DEBUG = True # in shell it was confimed as true
...
INSTALLED_APPS = [
...,
'backend'
]
...
ROOT_URLCONF = 'humm.urls'
...
BASE_DIR = Path(__file__).resolve().parent.parent
# BASE_DIR in shell give: WindowsPath('C:/django/humm/humm')
...
STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / 'static'
# STATIC_ROOT in shell give: WindowsPath('C:/django/humm/humm/static')
...
MEDIA_URL = 'media/'
MEDIA_ROOT = BASE_DIR / 'media'
# MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# both ways, in shell MEDIA_ROOT give: 'C:\\django\\humm\\humm\\media'
What I'm doing wrong ?
What can I do to show the uploaded images in admin interface ?