Skip to content
Django
6. Static & Media Files

Add Static & Media Files

1. Install Pillow

Terminal
pip install Pillow

Settings Configuration

Add the following code to the settings.py file to configure static and media files.

settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
 
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Adding URL Patterns

Add the following code to the urls.py file to serve static files during development.

urls.py
from django.conf import settings
from django.conf.urls.static import static
 
urlpatterns = [
    # your paths are here ...
]
 
if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Resize Image

When you want to resize the image whenever you upload an image. When you upload an image, you can resize it using the following code.

  • It can be done by overriding save method.
models.py
# models.py
from PIL import Image
 
class Profile(models.Model):
    # ...
 
    # Override save() method
    def save(self):
        super().save()
 
        img = Image.open(self.image.path)
 
        if img.height > 300 or img.width > 300:
            output_size = (300,300)
            img.thumbnail(output_size)
            img.save(self.image.path)

2. Collect Static Files

Collect all static files in one folder. It is used when you deploy your project.

Collect Static Files

Terminal
python manage.py collectstatic

Add Static & Media Files

Add the static and media files in the urls.py file.

urls.py
from django.conf import settings
from django.conf.urls.static import static
 
urlpatterns = [
    # your paths are here ...
]
 
# or
 
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)