Create a folder named 'static' in your root directory with 2 child folders of css and js to keep your static
files separated and easy to manage. In the static/css folder you can create your CSS files, usually starting
with base.css.
Create a separate 'media' folder in your root directory to store any images that you will use in your website.
Updating settings.py
To ensure that Django can find your CSS, JS, and media files, you will need to make sure that the paths are
defined in settings.py correctly. This can be done under the Static files section.
Now when you link your CSS files at the top of your HTML files you can use the {% static %}
templating function that will utilise the STATIC_URL in your settings.py file.
To link your media files to your pages during development you will need to add the
static()
function to the end of your urlpatterns in the project level urls.py file. This specifically handles uploaded
files during development (DEBUG = True). It tells Django's built-in development server where to look for files
requested under /media/.
Then add in the Cloudinary variables from your Cloudinary dashboard. I keep these at the top of the Static
files section. For security you should define these in your env.py file and access them from there.
Update your MEDIA_URL to have local files in development and externally hosted images during production.
if DEBUG:
# Local development settings
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
else:
# Production (Cloudinary)
MEDIA_URL = f"https://res.cloudinary.com/{CLOUDINARY_NAME}/image/upload/f_auto,q_auto/"
MEDIA_URL_VIDEOS = f"https://res.cloudinary.com/{CLOUDINARY_NAME}/video/upload/"
When accessing the image sources in your website, you can copy the URL of the image in your Cloudinary
dashboard, notice most of it is the same as your MEDIA_URL variable and just tack on the rest e.g.
Whitenoise is perfect for storing your static files for deployment on services such as Heroku. It converts your
static files to staticfiles where Heroku will look for them by default. Start by installing whitenoise from
your terminal.
pip3 install whitenoise
Then update your settings.py file:
Add whitenoise to your INSTALLED_APPS
In your static files section add a STATICFILES_STORAGE variable linking to whitenoise.
Update your STATIC_ROOT variable to access staticfiles