Featured image of post Configure Media and Staticfiles in Django

Configure Media and Staticfiles in Django

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

# settings/

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

and then add some mapping url pattern on core/ to serve media on django development mode

# core/
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("", 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 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.

    "django.contrib.staticfiles", # <- make sure this installed app is exist
    # Third Party

open settings/ on core apps and add this line

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

add add some javascript or css inside static

Adding Staticfile
Adding Staticfile

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' %}">


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

Licensed under CC BY-NC-SA 4.0
Last updated on Feb 08, 2022 12:02 +0700
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy