Search code examples
djangodjango-templates

issue with django show image tried many ways to solve


template doest not show images

i use <img src="/static/logo_coorg.png" width="60" height="40">

and settings like :[ changed ]

STATIC_URL = 'static/'
MEDIA_URL  = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
PROJECT_ROOT = os.path.normpath(os.path.dirname(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')

and the url as :


urlpatterns = [   
    path('admin/', admin.site.urls),
    path('',include('erp.urls')),  
    
]
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

by this way one of my django website does not have any issue. but another new django website is really a desparate one with this error. i am trying to fix this since last 24+ hours. help is sought.


Solution

  • In your template file, first load the static files with:

    {% load static %}
    

    Then use the static template tag:

    <img  src="{% static '/logo_coorg.png' width="60" height="40" %}"
    

    When your DEBUG mode is False, you don't need to add URL patterns for MEDIA_URL or STATIC_URL because Django is not responsible for serving your static or media files. You can write it like this:

    from django.conf import settings
    
    
    if settings.DEBUG:
        urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
        urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    

    You should handle the media and static URL paths inside the Apache webserver config file to serve the static and media files. For example:

    Alias /media/  full_path_of_your_media_diractory
    <Directory full_path_of_your_media_diractory>
        Require all granted
    </Directory>
        
    Alias /static/ full_path_of_your_static_diractory  
    <Directory full_path_of_your_static_diractory>
        Require all granted
    </Directory>
    
    

    Check the slashes in the URLs (I might be wrong).

    If it still doesn't work, please add your directory structure and webserver configuration to the question.