Home > Software engineering >  Templates do not show image. Django
Templates do not show image. Django

Time:04-21

Here is what i tried to do:

in my settings.py:

TEMPLATES = [
        ...
        'OPTIONS': {
            'context_processors': [
                ...
                'django.template.context_processors.media',
            ],
        },
    },
]

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

i have also added this in my main urls.py: static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

And here's the code in my template:

<img 
    src="{{ product.image.url }}"
    alt="Not available"
    height="188px"
    style="margin: 10px 0"
    width="188px"
/>

CodePudding user response:

In my project, I have added main urlpatterns as :

urlpatterns = urlpatterns   \
static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

And it working fine.

CodePudding user response:

Try using this for your static file resource

STATIC_URL = '/static/'
STATIC_ROOT = 'staticfiles'
STATICFILES_DIRS = (
   os.path.join(BASE_DIR, 'static'),

)
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'

Move your images to a folder name images inside your static folder

Then call your image in this way in your template file

<img src="{% static 'images/your_image.png' %}">
  • Related