Menu

Templates and Static Files

Templates and Static Files

Django Templates

Django templates are HTML files that contain special syntax for injecting dynamic data. By default, Django looks for templates inside a templates/ subdirectory within each app.

Create this file structure:

The double nesting (app name inside templates) is a Django convention that prevents template name collisions between apps.

Using template inheritance to avoid repeating your layout:

The {% extends %} tag pulls in the base layout. The {% block %} tags define regions that child templates can override. This means your navbar, header, and footer are written once and inherited everywhere.

Template Tags and Filters

Template tags add logic to your templates. Template filters transform values for display.

Common template tags:

Common template filters:

Filters use the pipe | syntax and can be chained:

Managing Static Files

Static files are your CSS, JavaScript, and images. Django has a dedicated system for managing them.

In settings.py:

Create a static/ folder at the project root and reference files in your templates:

The {% load static %} tag at the top activates the static file helpers. The {% static %} tag generates the correct URL for each file, regardless of where your site is hosted.