django static media
- Set Up Static Files Directory: Define a directory to store static files by configuring the
STATIC_ROOT
variable in your Django settings file (settings.py
).
python
STATIC_ROOT = BASE_DIR / 'staticfiles'
- Define Static URL: Set the URL prefix for static files using the
STATIC_URL
variable in your Django settings file. This defines the URL pattern used to serve static files.
python
STATIC_URL = '/static/'
- Configure Static Files Finders: Include
'django.contrib.staticfiles.finders.FileSystemFinder'
and'django.contrib.staticfiles.finders.AppDirectoriesFinder'
in theSTATICFILES_FINDERS
list insettings.py
. These finders help locate static files in the filesystem and app directories.
python
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
- Create a Static Files Directory: Generate a directory named
static
within each Django app where you wish to store static files. Place your app-specific static files (e.g., CSS, JavaScript, images) within these directories.
your_app/
static/
your_app_name/
css/
style.css
js/
script.js
img/
image.jpg
- Load Static Files in Templates: In your HTML templates, load static files using the
{% static %}
template tag to reference the static files' URLs.
```html
```
- Collect Static Files (Deployment): When deploying your Django project, use the
collectstatic
management command to gather all static files from different apps into the designatedSTATIC_ROOT
directory.
bash
python manage.py collectstatic
- Serve Static Files (Deployment): Configure your production web server (e.g., Nginx, Apache) to serve static files from the
STATIC_ROOT
directory to serve static content efficiently in a production environment.