Search code examples
pythonhtmldjangodjango-modelsdjango-staticfiles

Image is not being accessed through port 8000(under development)


My image path is working but Idk why it's not able to display it, any help is appreciated

models.py

class movies(models.Model):
    Image = models.ImageField(blank=True, null=True)

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

settings.py

STATIC_URL = '/static/'

MEDIA_URL = '/media/'

MEDIA_ROOT = 'media'

home.html

{% for m in movies %}
    <img src="{{ m.Image.url }}" width="200px", height="300px">
{% endfor %}

Solution

  • So the problem was with the Media root, my path was fine but Django wasn't able to get it somehow, so I ran this code to automate Django to find media root by itself

    ENV_PATH = os.path.abspath(os.path.dirname(__file__))
    MEDIA_ROOT = os.path.join(ENV_PATH, 'media/')
    

    and made a debug condition in the urls.py to run the request if viewed under development or localhost

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