Search code examples
pythondjangodjango-staticfilesdjango-deployment

Django 2.2 staticfiles do not work in development


I'm making a new django app where a user can upload images and then they can be displayed on a page. I've read the django docs 10000 times through and I still don't understand why my images aren't loading (DEBUG = True)

All my images are going to where they're supposed to be and in the admin in my models django has the right path that leads to the image but it just won't load properly.

my setup in settings.py:

STATIC_URL = '/static/'
STATIC_ROOT = 'static' # live cdn such as AWS S3

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]


MEDIA_ROOT = os.path.join(STATIC_ROOT, 'media')
MEDIA_URL = '/img/'

my directories:

|- src
    |- myproject
        |- settings.py, views.py, urls.py etc
    |- myapp
        |- views.py urls.py models.py forms.py etc
    |- static (this folder is empty and appeared after running collectstatic
    |- templates
    |- db.sqlite3
    |- manage.py
|- static (this folder is OUTSIDE src)
    |- admin
        |- django admin stuff
    |- media
        |- img
            |- myimage.png

in models.py of myapp the imagefield upload_to = 'img/'

as i said, the images don't load on the page but to upload to static/media/img/image_name.png

I've been trying to fix this for ages but i can't get any help from anyone and django docs and other stackoverflow questions/answers have been of no help too.

I thank you for your help!


Solution

  • Serving files uploaded by a user during development¶

    During development, you can serve user-uploaded media files from MEDIA_ROOT using the django.views.static.serve() view.

    This is not suitable for production use! For some common deployment strategies, see Deploying static files.

    For example, if your MEDIA_URL is defined as /media/, you can do this by adding the following snippet to your urls.py:

    from django.conf import settings
    from django.conf.urls.static import static
    
    urlpatterns = [
        # ... the rest of your URLconf goes here ...
    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    

    https://docs.djangoproject.com/en/2.2/howto/static-files/