Managing static files
This episode covers:-
1.) How to add a CSS stylesheet file.
2.) How to use the static template tag.
3.) How to force CSS cache refresh.
- Setup :-
Terminal
cp -fr 12-Bootstrap 13-Static-Files-CSS
cd 13-Static-Files-CSS
source ../venv/bin/activate
- Creating a stylesheet file :-
Create a staticbase/css/site.css file in the base app folder. You have to create the folder structure manually:
Stylesheet file location
base
├── static # < here
│ └── base # < here
│ └── css # < here
│ ├── site.css # < here
Edit base.html file and copy the contents of the style element to the site.css file.
Let’s also add a bright red color for h1 elements so we can see that the CSS is working. The site.css file should now look like this:
basestaticbase/css/site.css
body {
padding-top: 5rem;
}
.starter-template {
padding: 3rem 1.5rem;
text-align: center;
}
h1 {
color: red;
}
Replace the style element in the base.html template…
base/templates/base/base.html
<style>
...
</style>
…with this line:
base/templates/base/base.html
<link rel="stylesheet" href="{% static 'base/css/site.css' \
%}">
Make sure to put this link element after the line that loads the bootstrap.min.css file.
Make the static tag available in the template by using the load tag on top of the base.html file:
base/templates/base/base.html
{% load static %} <!-- here -->
<!doctype html>
<html lang="en">
h1 elements should now be red:
You can now remove the red styling from the site.css file.
- In Details :-
1) Working with static files :-
Files like CSS, JavaScript and images are referred as static files. With images I mean static assets like background images, not user-uploaded files. We will deal with media files later when we allow users to upload files.
The django.contrib.staticfiles app helps you manage these static assets. It’s installed by default:
mysite/settings.py
INSTALLED_APPS = [
...
'django.contrib.staticfiles', # < here
'base',
'myapp',
]
With the development server the static files will be served automatically in debug mode. In production we will use the collectstatic command to collect all static files in one place. They are then typically served with something like Nginx from a single location like static:
Media and static files in production environment
├── media
│ └── images
│ ├── Agapanthus_africanus1.jpg
│ ...
├── mysite
│ ├── base
│ ├── db.sqlite3
│ ├── manage.py
├── static # < here
Later I will also show you how to serve these files from an Amazon AWS bucket.
2) Using the static tag :-
load tag loads tags and filters registered in other libraries. In this case we use it to enable the static tag for the template. You have to use {% load static %} in every template that uses the static tag. Even if the parent template already loads it.
static tag generates absolute URLS for the static files.
This…
Using static tag in templates
href="{% static 'base/css/site.css' %}"
…becomes this:
The resulting HTML
href="staticbase/css/site.css"
This might seem unnecessary because we could just hard-code the correct URL there: staticbase/css/site.css. But we could also be serving the static files from some other URL. With a proper configuration the same static tag could be generating these kind of links:
Serving static files from external location
https://static.mysite.com/base/css/site.css
OR
https://mysite.s3.amazonaws.comstaticbase/css/site.css
Changing this URL will be trivial since we are not hard-coding it in template files.
In general you should avoid hard-coding in templates when Django can generate the markup for you. This is especially helpful when providing URLS to views and translating paths.
3) Forcing cache refresh with versioning :-
You can also visit the style URL directly to see if the style file is served correctly:
Visiting the stylesheet path directly
/static/base/css/site.css
If you are not seeing styling changes even if the site.css seems to be working, your browser might be serving you stale content from a cache. In Chrome you can do this:
- Visit View > Developer > Developer Tools.
- Select Network and Disable cache.
- Keep the Developer Tools open.
There are similar Developer tools in all major browsers.
You can also force CSS refresh by adding a new GET parameter ?v=2 each time you make styling changes:
CSS versioning
<link rel="stylesheet" href="{% static 'base/css/site.css' \
%}?v=2">
Better yet is to let Django generate a hash with ManifestStaticFileStorage:
https://samuli.to/CSS-Versioning.
Summary
- You can override Bootstrap theming with custom stylesheets.
- static tag generates absolute URLS for static assets like CSS and JavaScript files.
- In local development it’s useful to disable browser caching.
- In production environment it’s a common technic to add a hash to the CSS link path so the stylesheet is not loaded from the visitor’s browser cache.
- Static files can also be served from an external location like Amazon AWS bucket.


No comments:
Post a Comment
If you have any doubts. Please let me know.