Search code examples
djangodjango-media

I am having an issue uploading an image with Django


I am currently working my way through a django project and am having trouble working with MEDIA and uploading an graph image.

Inside settings.py, I have added the below code.

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')`

HomePage.html:

<img src="{{ MEDIA_URL }}image.png" alt="Uploaded Image" style="max-width: 100%; height:     auto;">  

HomePage->urls.py

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Relative Path from the html file to the image: media/graph/upload/image.png

I get the error

Not Found: /graph/upload/image.png.

Main Project

--App
----settings.py 
--HomePage 
----HomePage.html 
----urls.py
--media 
----graph 
------upload 
--------image.png

Thank you for all your help! Let me know if you need anymore of the code, I just didn't want to make this super long if this is a simple error.

I've also tried hardcoding the path to the directory and that did not work either so I think I am misunderstanding something with Django.


Solution

  • if you want to use {{ MEDIA_URL }} in your templates, add django.template.context_processors.media in the context_processors option of TEMPLATES.

    TEMPLATES = [
        {
            "BACKEND": "django.template.backends.django.DjangoTemplates",
            "APP_DIRS": True,
            "OPTIONS": {
                "context_processors": [
                    "django.template.context_processors.media"
                ],
            },
        },
    ]