In Django can handle Upload media by user like image and etc, for example
- A user uploaded image, pdfs, doc files etc while publishing a post.
- Images of products in an e-commerce site.
- User’s profile image. etc…
Just as with static file to serve media file, add some settings on our settings file
Configuring Media Files
To serve media file, add some configuration on our settings file
- MEDIA_ROOT
- MEDIA_URL
# settings/base.py
# MEDIA URL
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media/")
and then add some mapping url pattern on core/urls.py
to serve media on django development mode
# core/urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings # <- Import this module
from django.conf.urls.static import static # <- Import this module
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("dashboard.urls")),
path("accounts/", include("accounts.urls")),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # <- then add this line
Configuring Staticfiles in django
Managing static assets such as CSS, Javascript, fonts are core components of any modern web application Django provides us a large degree of freedom and flexibility on managing and serving static assets in different environments.
In settings.py file inside the INSTALLED_APPS
list, there is an app called 'django.contrib.staticfiles'
, this baked in app manages the static files across the entire project during development as well in production.
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles", # <- make sure this installed app is exist
# Third Party
"django_filters",
]
open settings/base.py
on core
apps and add this line
STATIC_URL = "static/"
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
add add some javascript or css inside static
and then load the statifile on template, for example
<img src="{% static 'img/path_to_the_img' %}">
<script src="{% static 'img/path_to_the_script' %}"></script>
<link rel="stylesheet" href="{% static 'css/base.css' %}">
Conclusion
Configure Media and Staticfile is important step to help customize interactive website using custom javascript and css file, interested with my article?, or need my service to building website or data scraping service you can contact me on fiverr or on upwork