Примечание
Если вы использовали ранее стороннее приложение django-staticfiles, django.contrib.staticfiles покажется вам очень знакомым. Это потому, что у них одинаковый код, django.contrib.staticfiles изначально было приложением django-staticfiles, которое добавили в Django 1.3.
Если вам необходимо обновиться с django-staticfiles, смотрите раздел Обновление с django-staticfiles ниже.
Расположите статические файлы там, где staticfiles сможет их найти.
По умолчанию это каталог ``static``в приложениях, которые добавлены в INSTALLED_APPS.
Ваш проект возможно будет содержать статические файлы, которые не относятся ни к одному из приложений. Настройка STATICFILES_DIRS указывает каталоги, которые проверяются на наличие статических файлов. По умолчанию эта настройка пустая. Подробности смотрите в описании настройки STATICFILES_DIRS.
Так же смотрите описание настройки STATICFILES_FINDERS что бы узнать как staticfiles ищет файлы.
Убедитесь что django.contrib.staticfiles добавлено INSTALLED_APPS.
Для разработки, если вы используете runserver или добавили staticfiles_urlpatterns) из STATIC_URL /static/.
Вам также понадобиться указать путь к файлам в шаблонах. Самый простой способ добавить процессор контекста который позволит использовать следующий код:
<img src="{{ STATIC_URL }}images/hi.jpg" />
Подробности смотрите в разделе Referring to static files in templates.
Set the STATIC_URL setting to the public URL for your static files (in most cases, the default value of /static/ is just fine).
Set the STATIC_ROOT setting to point to the filesystem path you’d like your static files collected to when you use the collectstatic management command. For example:
STATIC_ROOT = "/home/jacob/projects/mysite.com/sitestatic"
Run the collectstatic management command:
./manage.py collectstatic
This’ll churn through your static file storage and copy them into the directory given by STATIC_ROOT.
Deploy those files by configuring your webserver of choice to serve the files in STATIC_ROOT at STATIC_URL.
Serving static files in production covers some common deployment strategies for static files.
Примечание
In previous versions of Django, it was common to place static assets in MEDIA_ROOT along with user-uploaded files, and serve them both at MEDIA_URL. Part of the purpose of introducing the staticfiles app is to make it easier to keep static files separate from user-uploaded files.
For this reason, you need to make your MEDIA_ROOT and MEDIA_URL different from your STATIC_ROOT and STATIC_URL. You will need to arrange for serving of files in MEDIA_ROOT yourself; staticfiles does not deal with user-uploaded files at all. You can, however, use django.views.static.serve() view for serving MEDIA_ROOT in development; see Serving other directories.
<img src="http://static.example.com/static/myimage.jpg" />
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
)
<img src="{{ STATIC_URL }}images/hi.jpg" />
Примечание
There is also a template tag named static in Django’s core set of built in template tags which has the same argument signature but only uses urlparse.urljoin() with the STATIC_URL setting and the given path. This has the disadvantage of not being able to easily switch the storage backend without changing the templates, so in doubt use the staticfiles static template tag.
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf goes here ...
urlpatterns += staticfiles_urlpatterns()
Предупреждение
This will only work if DEBUG is True.
That’s because this view is grossly inefficient and probably insecure. This is only intended for local development, and should never be used in production.
Additionally, when using staticfiles_urlpatterns your STATIC_URL setting can’t be empty or a full URL, such as http://static.example.com/.
from django.conf import settings
# ... the rest of your URLconf goes here ...
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Примечание
This helper function will only be operational in debug mode and if the given prefix is local (e.g. /static/) and not a URL (e.g. http://static.example.com/).
from fabric.api import *
# Hosts to deploy onto
env.hosts = ['www1.example.com', 'www2.example.com']
# Where your project code lives on the server
env.project_root = '/home/www/myproject'
def deploy_static():
with cd(env.project_root):
run('./manage.py collectstatic -v0 --noinput')
from fabric.api import *
from fabric.contrib import project
# Where the static files get collected locally
env.local_static_root = '/tmp/static'
# Where the static files should go remotely
env.remote_static_root = '/home/www/static.example.com'
@roles('static')
def deploy_static():
local('./manage.py collectstatic')
project.rysnc_project(
remote_dir = env.remote_static_root,
local_dir = env.local_static_root,
delete = True
)
STATICFILES_STORAGE = 'myproject.storage.S3Storage'
См.также
The django-storages project is a 3rd party app that provides many storage backends for many common file storage APIs (including S3).
Aug 21, 2013