Search code examples
pythondjangodjango-admin

Django image is not displaying in developement environment


I'm trying add image in model with an Imagefield

Folder Structure:

/base
    /migrations
    /tempelates
    ...
    admin.py
    models.py
    urls.py
    ...
/env
/static
    /images
        avatar.png
    /styles
    /png
/networth_tracker/
/tempelates/
db.sqlite3
manage.py
pp1.jpg  #image I uploaded from admin site
pp2.jpg  #image I uploaded from admin site
pp3.jpg  #image I uploaded from admin site

/base/models.py

class Account(models.Model):
    ...
    logo = models.ImageField(null=True,default="avatar.png")
    ....

    class Meta:
        ordering = ['-updated', '-created']

    def __str__(self):
        return self.name

/networth_tracker/urls.py

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('base.urls')),
]

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIAFILES_DIRS)

/networth_tracker/settings.py

...
STATIC_URL = 'static/'
STATICFILES_DIRS = [BASE_DIR / "static"]

MEDIA_URL = '/images/'
MEDIAFILES_DIRS = BASE_DIR / "static/images"
...

Issue:

  1. I upload an image from admin site
  2. I tried to view the image directly in admin site and getting following error -- it searching for image in 127.0.0.1/images/pp1.jpg and returning page not found
  3. Image is uploading in / (root dir) instead of /static/images/ (media dir) Error on clicking image link from django admin site

I tried alternatives which is also not worked:

  1. I tried by adding upload_to="static/images" in ImageField models.py
class Account(models.Model):
   ...
   logo = models.ImageField(null=True,default="avatar.png", upload_to="static/images")
   ...
    
   class Meta:
        ordering = ['-updated', '-created']

    def __str__(self):
        return self.name

  1. It uploaded the image into the static/images/ folder, but getting following error enter image description here

Solution

  • MEDIAFILES_DIRS - there is no such option. You need to set STATIC_ROOT, MEDIA_ROOT.

    docs