Python Forum

Full Version: Django images will not load
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to make a hotel reservation app, but my images will not load. I am using Django and Bootstrap

I have my pictures in a media directory in the main directory of my project (with manage.py, myapp, myproject, venv).

I am pointing to these in settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
And here is the div where I want the image to display

<div class='p-4 m-4' style="height: 300px; background-color: rgba(255,0,0,0.1);">
<img src="/media/pic1.jpg" alt="Photo 1">
</div>
The image icon is showing in my development browser than an image is coming up, but it is not loading.

Does anyone have any idea why?
Hi @pythonpaul32

I'm not familiar with Django, I'm using my self Flask...

Did you have look in the UNIX permissions of those files ? I guess the user that run either Django or your webserver should have permissions to do so.

Cheers
You need to import the media folder. Put these lines of code in your urls.py

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
   #urls
   #...
 ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 
https://docs.djangoproject.com/en/4.2/ho...tic-files/

Hope this helps..
look!
In your div section the image path you provided in the src attribute of the <img> tag is correct.
But you have to use {% url %} template tag to generate the image URL dynamically For example:-

<div class='p-4 m-4' style="height: 300px; background-color: rgba(255,0,0,0.1);">
<img src="{% url 'image_url_name' 'pic1.jpg' %}" alt="Photo 1">
</div>

* In the above code replace 'image_url_name' with the name of the URL pattern you have defined for serving images in your Django project.

* Now next step is to serve media files during development in your project's urls.py file. For that use static() function like this:-

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
# Your existing URL patterns
]

# Serve media files during development
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

* in the above code the static() function is used to serve media files during development.

*Now cross check your settings.py file that whether media handling is properly defined or not like this:-

# Media settings
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

* Now run your django development server and your issue will be resolved.