python / intermediate
Snippet
Django Static Files Konfiguration und Manifest
Djangos staticfiles App sammelt Dateien von Apps und STATICFILES_DIRS in STATIC_ROOT für Deployment. ManifestStaticFilesStorage hängt Content-Hashes an Dateinamen an für aggressives Browser-Caching. Das {% static %}-Template-Tag generiert korrekte 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
Erklärung
1
STATICFILES_DIRS
Liste der Verzeichnisse wo Django neben Apps nach statischen Dateien sucht
2
ManifestStaticFilesStorage
Fügt Content-basierten Hash zu Dateinamen hinzu für Cache-Busting
3
STATIC_ROOT
Verzeichnis wo collectstatic alle statischen Dateien für Produktion sammelt
4
{% static 'images/logo.svg' %}
Template-Tag das URL mit STATIC_URL-Präfix generiert
5
?v=2 (Query-Parameter)
Manuelle Cache-Busting-Technik bei Verwendung von ManifestStaticFilesStorage