🌐
Django
docs.djangoproject.com › en › 6.0 › ref › contrib › staticfiles
The staticfiles app | Django documentation | Django
Due to the requirement of running collectstatic, this storage typically shouldn’t be used when running tests as collectstatic isn’t run as part of the normal test setup. During testing, ensure that staticfiles storage backend in the STORAGES setting is set to something else like 'django.contrib.staticfiles.storage.StaticFilesStorage' (the default).
🌐
Django
docs.djangoproject.com › en › 6.0 › howto › static-files
How to manage static files (e.g. images, JavaScript, CSS) | Django documentation | Django
django.contrib.staticfiles provides a convenience management command for gathering static files in a single directory so you can serve them easily. Set the STATIC_ROOT setting to the directory from which you’d like to serve these files, for ...
🌐
LearnDjango
learndjango.com › tutorials › django-static-files
Django Static Files | LearnDjango.com
4 days ago - # django_project/settings.py STATIC_URL = "static/" STATICFILES_DIRS = [BASE_DIR / "static"] # new · Next up is STATIC_ROOT which sets the absolute location of these collected files, typically called staticfiles. In other words, when collectstatic is run locally, it will combine all available static files, as defined by STATICFILES_DIRS, and place them within a directory called staticfiles.
🌐
Readthedocs
official-django-docs.readthedocs.io › en › latest › ref › contrib › staticfiles.html
The staticfiles app — Django 1.7a2 documentation
If you would like different permissions for these files and/or directories, you can subclass either of the static files storage classes and specify the file_permissions_mode and/or directory_permissions_mode parameters, respectively. For example: from django.contrib.staticfiles import storage ...
🌐
Django
django.readthedocs.io › en › stable › ref › contrib › staticfiles.html
The staticfiles app — Django 5.2.9 documentation
Due to the requirement of running collectstatic, this storage typically shouldn’t be used when running tests as collectstatic isn’t run as part of the normal test setup. During testing, ensure that staticfiles storage backend in the STORAGES setting is set to something else like 'django.contrib.staticfiles.storage.StaticFilesStorage' (the default).
🌐
SitePoint
sitepoint.com › blog › django › managing static files in django: a comprehensive guide
Managing Static Files in Django: A Comprehensive Guide — SitePoint
November 15, 2024 - You should note that in Django ... serve static files. In this scenario, any changes made to static files, such as CSS, JavaScript, or images, are automatically detected and applied by Django....
🌐
350
act.350.org › django_docs › ref › contrib › staticfiles.html
The staticfiles app — Django 1.8.19 documentation
Due to the requirement of running collectstatic, this storage typically shouldn’t be used when running tests as collectstatic isn’t run as part of the normal test setup. During testing, ensure that the STATICFILES_STORAGE setting is set to something else like 'django.contrib.staticfile...
🌐
Pypy-django
pypy-django.github.io › blog › 2024 › 07 › 17 › mastering-django-static-file-settings-static_url-static_root--staticfiles_dirs
Mastering Django Static File Settings: STATIC_URL, STATIC_ROOT & STATICFILES_DIRS - Django Organization
The STATICFILES_DIRS setting allows you to include additional directories for static files. When deploying, you run python manage.py collectstatic to gather all static files into the directory specified by STATIC_ROOT. Static files are then served by the web server (e.g., Nginx, Apache) rather ...
🌐
Michelepasin
michelepasin.org › blog › 2012 › 01 › 24 › setting-up-the-new-staticfiles-app-on-django-1-3 › index.html
Setting up the new 'staticfiles' app on Django 1.3 | Blogs | Michele Pasin
The only difference: the static files are delivered directly by Apache, bypassing Django (to make it faster). The new way of declaring these variables is this instead: MEDIA_URL = '/media/uploads/' STATIC_URL = '/media/static/' ADMIN_MEDIA_PREFIX = '/media/static/admin/' # Absolute path to the directory that holds media uploaded # I keep the uploads folder at the project-root level server MEDIA_ROOT = os.path.join(SITE_ROOT, 'uploads') # physical location of extra static files in development server STATICFILES_DIRS = ( os.path.join(SITE_ROOT, 'myproject/static'), ) # path used with "python manage.py collectstatic" # I normally put this at the project-root level that contains also the wsgi files for apache STATIC_ROOT = os.path.join(SITE_ROOT, 'apache/static')
🌐
TestDriven.io
testdriven.io › blog › django-static-files
Working with Static and Media Files in Django | TestDriven.io
January 28, 2024 - Instead, always put them in the directories associated with the STATICFILES_DIRS setting or <APP_NAME>/static/. Do not use the development server in production. Use a production-grade WSGI application server instead.
Find elsewhere
🌐
Django
django.readthedocs.io › en › 1.4.X › howto › static-files.html
Managing static files — Django 1.4.22 documentation
This will inspect your STATIC_URL setting and wire up the view to serve static files accordingly. Don’t forget to set the STATICFILES_DIRS setting appropriately to let django.contrib.staticfiles know where to look for files additionally to files in app directories.
🌐
Django
docs.djangoproject.com › en › 3.2 › howto › static-files
Managing static files (e.g. images, JavaScript, CSS) | Django documentation | Django
August 20, 2021 - django.contrib.staticfiles provides a convenience management command for gathering static files in a single directory so you can serve them easily. Set the STATIC_ROOT setting to the directory from which you’d like to serve these files, for ...
🌐
DigitalOcean
digitalocean.com › community › tutorials › working-with-django-templates-static-files
Working with Django Templates & Static Files | DigitalOcean
September 15, 2020 - Let’s make the celebrity’s networth field in the data template more readable by using some of these filters. To use Django’s humanize filters, you first need to edit some settings. Open up djangotemplates/settings.py and edit the INSTALLED_APPS list to this: # djangotemplates/djangotemplates/settings.py ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', # Add this line.
🌐
Waltercruz
waltercruz.github.io › django-l10n-portuguese › howto › static-files.html
Managing static files — Django v1.3.1 documentation
This will inspect your STATIC_URL setting and wire up the view to serve static files accordingly. Don't forget to set the STATICFILES_DIRS setting appropriately to let django.contrib.staticfiles know where to look for files additionally to files in app directories.
Top answer
1 of 2
10

Using Django 1.3 django.contrib.staticfiles will take care of serving everything for you during development. You don't need to do anything particular in the urls.py. I wrote a little guide for myself after the Django 1.3 update that covers the settings to use:

# idiom to get path of project
import os
PROJECT_PATH = os.path.dirname(os.path.abspath(__file__))
# url prefix for user uploaded files, stuff that django has to serve directly
MEDIA_URL = '/media/'
# url prefix for static files like css, js, images
STATIC_URL = '/static/'
# url prefix for *static* /admin media
ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'
# path to django-served media
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')
# path used for collectstatic, *where the webserver not django will expect to find files*
STATIC_ROOT = '/home/user/public_html/static'
# path to directories containing static files for django project, apps, etc, css/js
STATICFILES_DIRS = (
    os.path.join(PROJECT_PATH, 'static'),
)
# List of finder classes that know how to find static files in various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
) 
# Required for all the magic
INSTALLED_APPS = (
    'django.contrib.staticfiles',
)

Refer to the docs for details: http://docs.djangoproject.com/en/1.3/howto/static-files/.

I use nginx and uwsgi for serving django apps in production (I use runserver for development). I symlink my /static and /media folders (from my django project) into /var/www/vhosts/domain.com/html for nginx to find. You could also use the collectstatic command instead of symlinking. If it can't find a static file it falls back to uwsgi (which is running the django app).

Instead of uwsgi you could use fast-cgi, or proxy_pass or whatever you want. I prefer uwsgi because it has an incredible number of features and great performance. I run uwsgi as a daemon with: uwsgi --emperor '/srv/*/*.ini'. This is a fairly new option, it tells uwsgi to scan a given path for configuration files. When the emperor uwsgi daemon finds a configuration file it launches a new instance of uwsgi using the configuration found. If you change your configuration the emperor uwsgi daemon will notice and restart your app for you. You can also touch the config file to reload like with mod_wsgi, and it's really easy to setup new apps once you have everything configured initially.

The path conventions I follow are:

/srv/venv/ - virtualenv for project
/srv/venv/app.ini - configuration for uwsgi
/srv/venv/app.sock - uwsgi sock for django
/srv/venv/app.wsgi - wsgi file for uwsgi
/srv/venv/proj - django project
/srv/venv/proj/settings.py - project settings file
/srv/venv/proj/static - static files dir, linked into var/www/vhosts/domain.com/html
/srv/venv/proj/static/admin - admin static files, linked as well
/srv/venv/proj/media - media files dir
/var/www/vhosts/domain.com/html - base directory for nginx to serve static resources from

This is my nginx.conf:

location / {
    root /var/www/vhosts/domain.com/html;
    index index.html index.html;
    error_page 404 403 = @uwsgi;
    log_not_found  off;
}

location @uwsgi {
    internal;
    include /etc/nginx/uwsgi_params;
    uwsgi_pass unix:/srv/venv/app.sock;
}

My uwsgi ini file (you can also use xml/yaml/etc):

[uwsgi]
home = /srv/%n
pp = /srv/%n
wsgi-file = /srv/%n/%n.wsgi
socket = /srv/%n/%n.sock
single-intepreter = true
master = true
processes = 2
logto = /srv/%n/%n.log

You should also check out gunicorn, it has really nice django integration and good performance.

2 of 2
2

I'm putting this here in case someone wants an example of how to do this for Apache and WSGI. The question title is worded such that it's not just covering nginx.

Apache/WSGI Daemon

In my deployment, I decided to keep the database connection info out of the settings.py file. Instead I have a path /etc/django which contains the files with the database configuration. This is covered in some detail in an answer to another question. However, as a side effect, I can check for the presence of these files and the project being in a certain path to determine if this is running as a deployment, and in settings.py I define the settings IS_DEV, IS_BETA, and IS_PROD as True or False. Finding the project's directory from settings.py is just:

# Find where we live.
import os
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))

Anything that needs a path into the project uses BASE_DIR. So in urls.py, I have at the end:

# Only serve static media if in development (runserver) mode.
if settings.IS_DEV:
    urlpatterns += patterns('',
        url(r'^static/(?P<path>.*)$', 'django.views.static.serve', 
            {'document_root': settings.MEDIA_ROOT, 
            'show_indexes': True}),
    )

(I also have another URL in there that I use for UI testing and don't want on beta or production.)

This covers the development server case. For production, I just have to set the Apache configuration up to serve the static stuff. (This is an intranet application with low to medium load, so I don't have a lightweight webserver like lighttpd to serve the static stuff, contrary to the Django docs' recommendation.) Since I'm using Fedora Core, I add a django.conf file in /etc/httpd/conf.d that reads similar to:

WSGIDaemonProcess djangoproject threads=15
WSGISocketPrefix /var/run/wsgi/wsgi

Alias /django/static/ /var/www/djangoproject/static/
Alias /django/admin/media/ /usr/lib/python2.6/site-packages/django/contrib/admin/media/
WSGIScriptAlias /django /var/www/djangoproject/django.wsgi
WSGIProcessGroup djangoproject

<Directory /var/www/djangoproject>
    Order deny,allow
    Allow from all
</Directory>

<Directory /usr/lib/python2.6/site-packages/django/contrib/admin/media>
    Order deny,allow
    Allow from all
</Directory>

IIRC, the key here is to put your Alias lines before your WSGIScriptAlias line. Also make sure that there's no way for the user to download your code; I did that by putting the static stuff in a static directory that is not in my Django project. That's why BASE_DIR gives the directory containing the Django project directory.

You can omit the WSGISocketPrefix line. I have it because the admin wants the sockets in a non-default location.

My WSGI file is at /var/www/djangoproject/django.wsgi (i.e. /django.wsgi in the Mercurial repository) and contains something like:

import os
import sys

os.environ['DJANGO_SETTINGS_MODULE'] = 'djangoproject.settings'
os.environ['DB_CONFIG'] = '/etc/django/db_regular.py'
thisDir = os.path.dirname(__file__)
sys.path.append(thisDir)
sys.path.append(os.path.join(thisDir, 'djangoproject'))
sys.path.append(os.path.join(thisDir, 'lib'))

import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

The nice thing about WSGI daemons is that you just have to touch django.wsgi to restart your Django WSGI daemon; you don't need to reload or restart the Apache server. This makes the admin happy.

Finally, since my /var/www/djangoproject is just a Mercurial repo, I have the following in /var/www/djangoproject/.hg/hgrc:

[hooks]
changegroup.1=find . -name \*.py[co] -exec rm -f {} \;
changegroup.2=hg update
changegroup.3=chgrp -Rf djangoproject . || true
changegroup.4=chmod -Rf g+w,o-rwx . || true
changegroup.5=find . -type d -exec chmod -f g+xs {} \;
changegroup.6=touch django.wsgi # Reloads the app

This clears Python bytecode, updates the working copy, fixes up all the perms, and restarts the daemon whenever a developer pushes into deployment, so anyone in the djangoproject group can push into it and not just the last one who added a file. Needless to say, be careful who you put in the djangoproject group.


zeekay sets STATIC_URL, STATIC_ROOT, STATICFILES_DIRS, STATICFILES_FINDERS and uses "django.contrib.staticfiles" and "django.core.context_processors.static" in his settings. I don't have those since my code dates back to Django 1.1 and don't use {{ STATIC_ROOT }}.

Hope this helps.

🌐
GeeksforGeeks
geeksforgeeks.org › django-static-file
Django Static File - GeeksforGeeks
November 7, 2023 - INSTALLED_APPS = [ 'showstatic.apps.ShowstaticConfig', 'django.contrib.admin', 'django.contrib.auth, 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] now try to runserver once to confirm everything is working smoothly ... Now we create a static folder inside the main folder (checkstatic) where we will keep our static files. One can add your files (pdf, images, text files, or anything you want) in the static folder. ... urls.py: The code then appends additional URL patterns using the + operator. These patterns are used to serve media files during development.
🌐
W3Schools
w3schools.com › django › django_add_global_static_files.php
Django - Global Static Files
You will have to tell Django to also look for static files in the mystaticfiles folder in the root directory, this is done in the settings.py file: ... . . STATIC_ROOT = BASE_DIR / 'productionfiles' STATIC_URL = 'static/' #Add this in your ...
🌐
PythonAnywhere
help.pythonanywhere.com › pages › DjangoStaticFiles
How to setup static files in Django | PythonAnywhere Help
May 13, 2015 - There are 3 main things to do: set STATIC_ROOT in settings.py run python3.10 manage.py collectstatic (or python3.9 or python3.8 as appropriate) set up a Static Files entry on the PythonAnywhere Web t