Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Custom Static File Handlers in Django

Introduction

In Django, static files such as CSS, JavaScript, and images are served using a dedicated mechanism. By default, Django provides a way to handle static files, but there are cases where you might need a custom static file handler. This tutorial will guide you through the steps to create and configure custom static file handlers in Django.

Prerequisites

Before you proceed, ensure you have the following:

  • Basic understanding of Django framework.
  • Django installed in your environment.
  • A Django project setup.

Setting Up Static Files

By default, Django looks for static files in the static directory of each app and in the directories listed in the STATICFILES_DIRS setting. Let's configure the static files settings in your Django project.

Open your settings.py file and add the following:

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    BASE_DIR / "static",
]
                

Creating a Custom Static File Handler

To create a custom static file handler, you need to subclass django.views.static.serve. Here is a simple example of a custom static file handler that logs requests:

from django.http import HttpResponse
from django.views.static import serve
import logging

logger = logging.getLogger(__name__)

def custom_static_file_handler(request, path, document_root=None, show_indexes=False):
    logger.info(f"Serving static file: {path}")
    return serve(request, path, document_root, show_indexes)
                

Configuring URLs

Next, you need to configure the URLs to use your custom static file handler. Open your urls.py file and include the following:

from django.conf import settings
from django.conf.urls.static import static
from django.urls import re_path
from .views import custom_static_file_handler

urlpatterns = [
    # ... your other url patterns
]

if settings.DEBUG:
    urlpatterns += [
        re_path(r'^static/(?P.*)$', custom_static_file_handler, {
            'document_root': settings.STATIC_ROOT,
        }),
    ]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
                

Testing the Custom Handler

To test our custom static file handler, you need to start the Django development server and access a static file. The server logs should show the path of the static file being accessed.

Start the Django development server:

python manage.py runserver
                

Access a static file in your browser, such as:

http://127.0.0.1:8000/static/yourfile.css
                

Check the server logs to confirm the static file path is being logged:

INFO:__main__:Serving static file: yourfile.css

Conclusion

In this tutorial, we covered how to create and configure custom static file handlers in Django. This allows you to add custom logic when serving static files, such as logging or additional security checks. Custom static file handlers provide greater flexibility and control over how static files are handled in your Django applications.