python / intermediate
Snippet
Django Static Files Configuration and Manifest
Django's staticfiles app collects files from apps and STATICFILES_DIRS into STATIC_ROOT for deployment. ManifestStaticFilesStorage appends content hashes to filenames enabling aggressive browser caching. The {% static %} template tag generates correct URLs in templates.
snippet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# settings.pyimport osfrom django.contrib import staticfilesBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))STATIC_URL = '/static/'STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),]STATICFILES_FINDERS = ['django.contrib.staticfiles.finders.FileSystemFinder','django.contrib.staticfiles.finders.AppDirectoriesFinder','django.contrib.staticfiles.storage.ManifestStaticFilesStorage',]# models.py (versioned file reference)class Asset(models.Model):name = models.CharField(max_length=100)file = models.FileField(upload_to='assets/')def get_absolute_url(self):return self.file.url# template<img src="{% static 'images/logo.svg' %}" alt="Logo"><link href="{% static 'css/styles.css' %}?v=2" rel="stylesheet">
django
Breakdown
1
STATICFILES_DIRS
List of directories where Django searches for static files besides apps
2
ManifestStaticFilesStorage
Adds content-based hash to filenames (e.g., styles.css -> styles.a1b2c3.css) for cache busting
3
STATIC_ROOT
Directory where collectstatic command gathers all static files for production
4
{% static 'images/logo.svg' %}
Template tag that generates the URL with STATIC_URL prefix
5
?v=2 (query param)
Manual cache busting technique when using ManifestStaticFilesStorage