Follow this steps to load an image on your Django Template:

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

2. Create a folder named “media” under your project root directory, meaning the folder will be on the same level as your apps

3. Add these to your main urls.py

from . import views, settings
from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

4. In your model, use ImageField for the field being used for the image.

photo = models.ImageField(upload_to="image_gallery")

5. Add below to your template to load your images

If you are loading dynamically from a context object, use a syntax similar to this:

img src="{{ obj1.photo.url }}"

If you are loading statically, when the file name is already determined, use:

img src="/media/project_name/photo.png"<br>

LEAVE A REPLY

Please enter your comment!
Please enter your name here