Interview question
How do you serve static files and media files in Django? Django में static files और media files कैसे serve करें?
Answer
| Type | Purpose | Settings |
|---|---|---|
| Static files | CSS, JS, images bundled with your app code | STATIC_URL, STATICFILES_DIRS, STATIC_ROOT |
| Media files | User-uploaded content (profile pictures, documents) | MEDIA_URL, MEDIA_ROOT |
# settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'static'] # where Django looks in development
STATIC_ROOT = BASE_DIR / 'staticfiles' # where collectstatic gathers files for production
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media' # where uploaded files are stored
# In templates - loading and referencing static files
{% load static %}
<link rel='stylesheet' href="{% static 'css/style.css' %}">
<img src="{% static 'images/logo.png' %}" alt='Logo'>
# Serving media files - referencing an uploaded file via a model field
class Book(models.Model):
cover = models.ImageField(upload_to='book_covers/')
# In a template
<img src="{{ book.cover.url }}" alt="{{ book.title }}">
# urls.py - serving media files during DEVELOPMENT only
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... your other patterns ...
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# For PRODUCTION, static/media files should be served by a dedicated
# web server (Nginx) or cloud storage (AWS S3 via django-storages),
# NOT by Django itself - Django serving files directly is slow and
# insecure at scale
# Collecting all static files into STATIC_ROOT for deployment
# $ python manage.py collectstatic| Type | उद्देश्य | Settings |
|---|---|---|
| Static files | CSS, JS, images | STATIC_URL, STATICFILES_DIRS, STATIC_ROOT |
| Media files | User-uploaded content | MEDIA_URL, MEDIA_ROOT |
# settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'static']
STATIC_ROOT = BASE_DIR / 'staticfiles'
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
# Templates में static files
{% load static %}
<link rel='stylesheet' href="{% static 'css/style.css' %}">
<img src="{% static 'images/logo.png' %}" alt='Logo'>
class Book(models.Model):
cover = models.ImageField(upload_to='book_covers/')
<img src="{{ book.cover.url }}" alt="{{ book.title }}">
# urls.py - development में media files serve करना
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# Production में Nginx या S3 (django-storages) use करें, Django खुद नहीं
# Deployment के लिए static files collect करना
# $ python manage.py collectstaticWas this answer clear?