settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static')
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
urls.py
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('food/',include('foodApp.urls')),
] static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
HTML Template
<a href="">
<img src="{% static 'delivery.png' %}">
</a>
Folder Directory
food_delivery (Main Project)
-- food_delivery
-- foodApp
-- static (folder that puts images)
-- templates
-- manage.py
For loading images in Django, the HTML template could not correctly recognize the image that I am trying to indicate. I have a confusion where should I put the static folder in my project directory and I am not sure anything I am missing in the settings.py file in order to recognize the images inside the static folder directory. Can anyone can help me find out the solution in order to load images that are put under the static folder directory?
CodePudding user response:
You need to add the static configuration on top of the media configuration:
if settings.DEBUG:
urlpatterns = (
static(settings.STATIC_URL, document_root=settings.STATIC_ROOT))
urlpatterns = (
static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT))
Note the if settings.DEBUG
is not required as such as the static
function does check if the app is in debug mode. I just have it there as a reminder.
Of course, if you're not using MEDIA_ROOT
just remove it.
CodePudding user response:
Your directory structure seems good, but in settings.py
you must add STATICFILES_DIRS
:
STATIC_URL = '/static/'
MEDIA_URL = '/images/'
STATICFILES_DIRS = [
BASE_DIR / 'static'
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images')
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
and put delivery.png
in static
folder.
P.S.
I add the static
to urlpatterns
as an if
statement like below to avoid problems in upcoming deployments.
if settings.DEBUG:
urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
CodePudding user response:
#settings.py
INSTALLED_APPS = [
...
'django.contrib.staticfiles',
...
]
TEMPLATES = [
{...
'context_processors': [
'django.template.context_processors.media',
'django.template.context_processors.static',
],
...}
]
STATIC_URL = '/static/'
STATIC_ROOT = BASE_ROOT / 'static'
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_ROOT / 'media'
#urls.py
if settings.DEBUG:
urlpatterns = (
static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
)
#html
{% load static %}
<a href="">
<img src="{% static 'delivery.png' %}">
</a>