Django · Lesson 11 of 15
Static Files, Media and Caching
collectstatic, user uploads, WhiteNoise and the cache framework.
- Intermediate
- 15 min read
- 3 objectives
Before this lessonLesson 10: Testing Django Apps
What you will learn
- Serve static assets
- Save an uploaded file
- Cache a queryset
Your Progress
0 of 15 lessons 0%
- Lessons0 / 15
- Completed0
- Est. time left~ 4 hours
Create a free account to keep your progress on every device.
Static files (CSS, JS, images you ship) and media files (user uploads) are configured differently, and the cache framework sits next to both.
Static files
# settings
STATIC_URL = "static/"
STATIC_ROOT = BASE_DIR / "staticfiles" # collectstatic target
STATICFILES_DIRS = [BASE_DIR / "static"] # your source{% load static %}
<link rel="stylesheet" href="{% static 'app.css' %}">python manage.py collectstaticIn production, WhiteNoise serves compressed, hashed files from Django without Nginx for small apps: pip install whitenoise and add the middleware.
Uploads
class Profile(models.Model):
avatar = models.ImageField(upload_to="avatars/")
# settings
MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR / "media"Never serve MEDIA_ROOT with WhiteNoise in production; put uploads on S3 (django-storages) so the app servers stay stateless.
Caching
from django.core.cache import cache
from django.views.decorators.cache import cache_page
@cache_page(60 * 5)
def popular(request):
...
posts = cache.get_or_set("home-posts", lambda: list(Post.objects.all()[:10]), 60)