Django настройка статических файлов
Веб-приложения обычно требуют различные дополнительные файлы для своей работы (изображения, CSS, Javascript и др.). В Django их принято называть “статическими файлами”(прим.пер. - или “статика”). Django предоставляет приложение django.contrib.staticfiles для работы с ними.
Этот раздел описывает как работать с ними.
Раздача статических файлов при разработке.¶
Если вы используете django.contrib.staticfiles как описано ваше, runserver все сделает автоматически, если DEBUG равна True . Если django.contrib.staticfiles не добавлено в INSTALLED_APPS , вы можете раздавать статические файлы используя представление django.contrib.staticfiles.views.serve() .
Не используйте его на боевом сервере! Способы раздачи статических файлов описаны в разделе Развертывание статических файлов.
Например, если STATIC_URL равна /static/ , вы можете добавить следующий код в urls.py :
Также эта функция раздает файлы из каталога STATIC_ROOT не выполняя поиск всех статических файлов, как это делает django.contrib.staticfiles .
Learn more¶
For complete details on all the settings, commands, template tags, and other pieces included in django.contrib.staticfiles , see the staticfiles reference .
Static file development view¶
The static files tools are mostly designed to help with getting static files successfully deployed into production. This usually means a separate, dedicated static file server, which is a lot of overhead to mess with when developing locally. Thus, the staticfiles app ships with a quick and dirty helper view that you can use to serve files locally in development.
This view function serves static files in development.
This view 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.
To guess the served files’ content types, this view relies on the mimetypes module from the Python standard library, which itself relies on the underlying platform’s map files. If you find that this view doesn’t return proper content types for certain files, it is most likely that the platform’s map files are incorrect or need to be updated. This can be achieved, for example, by installing or updating the mailcap package on a Red Hat distribution, mime-support on a Debian distribution, or by editing the keys under HKEY_CLASSES_ROOT in the Windows registry.
This view is automatically enabled by runserver (with a DEBUG setting set to True ). To use the view with a different local development server, add the following snippet to the end of your primary URL configuration:
Note, the beginning of the pattern ( r'^static/' ) should be your STATIC_URL setting.
Since this is a bit finicky, there’s also a helper function that’ll do this for you:
This will return the proper URL pattern for serving static files to your already defined pattern list. Use it like this:
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 in addition to files in app directories.
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.
Learn More
Serving the site and your static files from the same server¶
If you want to serve your static files from the same server that’s already serving your site, the process may look something like:
- Push your code up to the deployment server.
- On the server, run collectstatic to copy all the static files into STATIC_ROOT .
- Configure your web server to serve the files in STATIC_ROOT under the URL STATIC_URL . For example, here’s how to do this with Apache and mod_wsgi .
You’ll probably want to automate this process, especially if you’ve got multiple web servers.
6. Загрузите скрипт в шаблон
Теперь для подключения JS-файла к проекту добавьте файл в «header.html». Файл должен вызываться так же, как и в случае с изображениями.
Не забудьте и о в верхней части страницы для корректной работы тегов.
4. Загрузите статический файл в свой HTML-шаблон
Теперь в выбранном шаблоне (например, в «home.html») загрузите статический файл в верхней части страницы.
Важно добавить до того, как добавлять изображение. В противном случае оно не будет загружено.
Support Django!
Создание файла script.js
В папке static > js создайте файл «script.js», в котором будут храниться все функции JavaScript.
Management Commands¶
django.contrib.staticfiles exposes three management commands.
Download:
Offline (Django 4.0): HTML | PDF | ePub
Provided by Read the Docs.
ManifestFilesMixin ¶
Use this mixin with a custom storage to append the MD5 hash of the file’s content to the filename as ManifestStaticFilesStorage does.
The manifest_storage argument was added.
Contents
2. Укажите статический URL Django в настройках
Теперь убедитесь, что статические файлы Django django.contrib.staticfiles указаны в списке установленных приложений в settings.py.
Они должны быть там по умолчанию.
После этого пролистайте в нижнюю часть файла настроек и укажите статический URL, если такого еще нет. Вы также можете указать статическую папку, чтобы Django знал, где искать статические файлы.
Не забудьте импортировать библиотеку os после добавления кода выше.
После завершения базовой настройки рассмотрим, как добавлять и показывать изображения в шаблонах, а также как подключить свои JavaScript и CSS файлы.
collectstatic ¶
Collects the static files into STATIC_ROOT .
Duplicate file names are by default resolved in a similar way to how template resolution works: the file that is first found in one of the specified locations will be used. If you’re confused, the findstatic command can help show you which files are found.
On subsequent collectstatic runs (if STATIC_ROOT isn’t empty), files are copied only if they have a modified timestamp greater than the timestamp of the file in STATIC_ROOT . Therefore if you remove an application from INSTALLED_APPS , it’s a good idea to use the collectstatic --clear option in order to remove stale static files.
Files are searched by using the enabled finders . The default is to look in all locations defined in STATICFILES_DIRS and in the 'static' directory of apps specified by the INSTALLED_APPS setting.
The collectstatic management command calls the post_process() method of the STATICFILES_STORAGE after each run and passes a list of paths that have been found by the management command. It also receives all command line options of collectstatic . This is used by the ManifestStaticFilesStorage by default.
By default, collected files receive permissions from FILE_UPLOAD_PERMISSIONS and collected directories receive permissions from FILE_UPLOAD_DIRECTORY_PERMISSIONS . 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:
Then set the STATICFILES_STORAGE setting to 'path.to.MyStaticFilesStorage' .
Do NOT prompt the user for input of any kind.
--ignore PATTERN , -i PATTERN ¶
Ignore files, directories, or paths matching this glob-style pattern. Use multiple times to ignore more. When specifying a path, always use forward slashes, even on Windows.
Do everything except modify the filesystem.
Clear the existing files before trying to copy or link the original file.
Create a symbolic link to each file instead of copying.
Don’t call the post_process() method of the configured STATICFILES_STORAGE storage backend.
Don’t ignore the common private glob-style patterns 'CVS' , '.*' and '*~' .
For a full list of options, refer to the commands own help by running:
Customizing the ignored pattern list¶
The default ignored pattern list, ['CVS', '.*', '*~'] , can be customized in a more persistent way than providing the --ignore command option at each collectstatic invocation. Provide a custom AppConfig class, override the ignore_patterns attribute of this class and replace 'django.contrib.staticfiles' with that class path in your INSTALLED_APPS setting:
findstatic ¶
Searches for one or more relative paths with the enabled finders.
By default, all matching locations are found. To only return the first match for each relative path, use the --first option:
This is a debugging aid; it’ll show you exactly which static file will be collected for a given path.
By setting the --verbosity flag to 0, you can suppress the extra output and just get the path names:
On the other hand, by setting the --verbosity flag to 2, you can get all the directories which were searched:
3. Создайте папку для изображений
Создайте папку в «static» специально для изображений. Назовите ее «img». Главное после этого правильно ссылаться на нее в шаблонах.
Learn more¶
This document has covered the basics and some common usage patterns. For complete details on all the settings, commands, template tags, and other pieces included in django.contrib.staticfiles , see the staticfiles reference .
Узнайте больше¶
Этот документ описывает основные и самые распостраненные практики. Подробности о настройках, командах, шаблонных тегах и других деталях, включая django.contrib.staticfiles , смотрите раздел о статических файлах.
Websites generally need to serve additional files such as images, JavaScript, or CSS. In Django, we refer to these files as “static files”. Django provides django.contrib.staticfiles to help you manage them.
This page describes how you can serve these static files.
Getting help
Deployment¶
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 example:
Run the collectstatic management command:
This will copy all files from your static folders into the STATIC_ROOT directory.
Use a web server of your choice to serve the files. How to deploy static files covers some common deployment strategies for static files.
Other Helpers¶
There are a few other helpers outside of the staticfiles app to work with static files:
- The django.template.context_processors.static() context processor which adds STATIC_URL to every template context rendered with RequestContext contexts.
- The builtin template tag static which takes a path and urljoins it with the static prefix STATIC_URL . If django.contrib.staticfiles is installed, the tag uses the url() method of the STATICFILES_STORAGE instead.
- The builtin template tag get_static_prefix which populates a template variable with the static prefix STATIC_URL to be used as a variable or directly.
- The similar template tag get_media_prefix which works like get_static_prefix but uses MEDIA_URL .
Browse
- Django 4.0 documentation
- How to manage static files (e.g. images, JavaScript, CSS)
- When your static files change, run collectstatic locally.
- Push your local STATIC_ROOT up to the static file server into the directory that’s being served. rsync is a common choice for this step since it only needs to transfer the bits of static files that have changed.
- The @import rule and url() statement of Cascading Style Sheets.
- The source map comment in JavaScript.
- the STATICFILES_STORAGE setting is set to 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
- the DEBUG setting is set to False
- you’ve collected all your static files by using the collectstatic management command
Serving static files from a cloud service or CDN¶
Another common tactic is to serve static files from a cloud storage provider like Amazon’s S3 and/or a CDN (content delivery network). This lets you ignore the problems of serving static files and can often make for faster-loading web pages (especially when using a CDN).
When using these services, the basic workflow would look a bit like the above, except that instead of using rsync to transfer your static files to the server you’d need to transfer the static files to the storage provider or CDN.
There’s any number of ways you might do this, but if the provider has an API, you can use a custom file storage backend to integrate the CDN with your Django project. If you’ve written or are using a 3rd party custom storage backend, you can tell collectstatic to use it by setting STATICFILES_STORAGE to the storage engine.
For example, if you’ve written an S3 storage backend in myproject.storage.S3Storage you could use it with:
Once that’s done, all you have to do is run collectstatic and your static files would be pushed through your storage package up to S3. If you later needed to switch to a different storage provider, you may only have to change your STATICFILES_STORAGE setting.
Ошибки, связанные с загрузкой статических файлов Django
Если вы получили ошибку «Invalid block tag on line 8: ‘static’, expected ‘endblock’. Did you forget to register or load this tag?», то вы наверняка забыли добавить тег загрузки статических файлов в верхней части страницы: до вызова самого изображения.
Такая ошибка «Could not parse the remainder: ‘/photo.jpg’ from ‘img/photo.jpg’» значит, что вы забыли добавить кавычки вокруг ссылки на изображения. В этом случае нужно использовать две пары кавычек: одни для всего содержимого src , а вторые — для ссылки на изображение.
«Invalid block tag on line 9: »static/img/photo.jpg», expected ‘endblock’. Did you forget to register or load this tag?» говорит о том, что вы случайно добавили тег static в URL.
Если страница не загружается, и появляется следующая ошибка: «django.core.exceptions.ImproperlyConfigured: You’re using the staticfiles app without having set the required STATIC_URL setting», то это указывает на то, что вы забыли указать статический URL в файле настроек. Его нужно задать в settings.py и сохранить документ.
Наконец, если вы не получаете ошибку, но изображение не отображается, то убедитесь, что вы правильно используете тег.
Serving static files from a dedicated server¶
Configuring these servers is out of scope of this document; check each server’s respective documentation for instructions.
Since your static file server won’t be running Django, you’ll need to modify the deployment strategy to look something like:
Configuring static files¶
Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS .
In your settings file, define STATIC_URL , for example:
In your templates, use the static template tag to build the URL for the given relative path using the configured STATICFILES_STORAGE .
Store your static files in a folder called static in your app. For example my_app/static/my_app/example.jpg .
Serving the files
In addition to these configuration steps, you’ll also need to actually serve the static files.
During development, if you use django.contrib.staticfiles , this will be done automatically by runserver when DEBUG is set to True (see django.contrib.staticfiles.views.serve() ).
This method is grossly inefficient and probably insecure, so it is unsuitable for production.
See How to deploy static files for proper strategies to serve static files in production environments.
Your project will probably also have static assets that aren’t tied to a particular app. In addition to using a static/ directory inside your apps, you can define a list of directories ( STATICFILES_DIRS ) in your settings file where Django will also look for static files. For example:
See the documentation for the STATICFILES_FINDERS setting for details on how staticfiles finds your files.
Static file namespacing
Now we might be able to get away with putting our static files directly in my_app/static/ (rather than creating another my_app subdirectory), but it would actually be a bad idea. Django will use the first static file it finds whose name matches, and if you had a static file with the same name in a different application, Django would be unable to distinguish between them. We need to be able to point Django at the right one, and the best way to ensure this is by namespacing them. That is, by putting those static files inside another directory named for the application itself.
You can namespace static assets in STATICFILES_DIRS by specifying prefixes .
8. Загрузите ссылку на CSS в шаблон
Для подключения собственных стилей к проекту, добавьте HTML-элемент в «header.html». Файл вызывается так же, как изображения и JS-файлы.
И снова не забудьте о в верхней части страницы. Если не добавить эту строку, то будет ошибка.
Если класс custom добавить к container вы увидите изменения:
Serving files uploaded by a user during development¶
During development, you can serve user-uploaded media files from MEDIA_ROOT using the django.views.static.serve() view.
This is not suitable for production use! For some common deployment strategies, see How to deploy static files .
For example, if your MEDIA_URL is defined as media/ , you can do this by adding the following snippet to your ROOT_URLCONF :
Settings¶
See staticfiles settings for details on the following settings:
Support Us
© 2005-2022 Django Software Foundation and individual contributors. Django is a registered trademark of the Django Software Foundation.
Если вы искали способ добавить изображения, стили и js в свой проект на Django, то пришли по адресу.
Что такое статические файлы в Django?
Изображения, JS и CSS-файлы называются статическими файлами или ассетами проекта Django.Обучение с трудоустройством
Я создал этот блог в 2018 году, чтобы распространять полезные учебные материалы, документации и уроки на русском. На сайте опубликовано множество статей по основам python и библиотекам, уроков для начинающих и примеров написания программ.
django.contrib.staticfiles collects static files from each of your applications (and any other places you specify) into a single location that can easily be served in production.
For an introduction to the static files app and some usage examples, see How to manage static files (e.g. images, JavaScript, CSS) . For guidelines on deploying static files, see How to deploy static files .
1. Создадим папку для статических файлов
В папке проекта Django создайте новую папку «static». В примере выше она находится в директории «dstatic».
Развертывание¶
django.contrib.staticfiles предоставляет команду, чтобы собрать все статические файлы в одном каталоге.
Укажите в STATIC_ROOT каталог, из которого будут раздаваться статические файлы, например:
Она скопирует все статические файлы в каталоге STATIC_ROOT .
Используйте любой веб-сервер для раздачи этих файлов. Способы раздачи статических файлов описаны в разделе Развертывание статических файлов.
Specialized test case to support ‘live testing’¶
This unittest TestCase subclass extends django.test.LiveServerTestCase .
But given the fact that it makes use of the django.contrib.staticfiles.views.serve() view described above, it can transparently overlay at test execution-time the assets provided by the staticfiles finders. This means you don’t need to run collectstatic before or as a part of your tests setup.
The basic outline of putting static files into production consists of two steps: run the collectstatic command when static files change, then arrange for the collected static files directory ( STATIC_ROOT ) to be moved to the static file server and served. Depending on STATICFILES_STORAGE , files may need to be moved to a new location manually or the post_process method of the Storage class might take care of that.
As with all deployment tasks, the devil’s in the details. Every production setup will be a bit different, so you’ll need to adapt the basic outline to fit your needs. Below are a few common patterns that might help.
Follow Us
runserver ¶
Overrides the core runserver command if the staticfiles app is installed and adds automatic serving of static files. File serving doesn’t run through MIDDLEWARE .
The command adds these options:
Use the --nostatic option to disable serving of static files with the staticfiles app entirely. This option is only available if the staticfiles app is in your project’s INSTALLED_APPS setting.
Use the --insecure option to force serving of static files with the staticfiles app even if the DEBUG setting is False . By using this you acknowledge the fact that it’s grossly inefficient and probably insecure. This is only intended for local development, should never be used in production and is only available if the staticfiles app is in your project’s INSTALLED_APPS setting.
Get Involved
Testing¶
Because of this, staticfiles ships its own django.contrib.staticfiles.testing.StaticLiveServerTestCase , a subclass of the built-in one that has the ability to transparently serve all the assets during execution of these tests in a way very similar to what we get at development time with DEBUG = True , i.e. without having to collect them using collectstatic first.
ManifestStaticFilesStorage ¶
A subclass of the StaticFilesStorage storage backend which stores the file names it handles by appending the MD5 hash of the file’s content to the filename. For example, the file css/styles.css would also be saved as css/styles.55e7cbb9ba48.css .
The purpose of this storage is to keep serving the old files in case some pages still refer to those files, e.g. because they are cached by you or a 3rd party proxy server. Additionally, it’s very helpful if you want to apply far future Expires headers to the deployed files to speed up the load time for subsequent page visits.
The storage backend automatically replaces the paths found in the saved files matching other saved files with the path of the cached copy (using the post_process() method). The regular expressions used to find those paths ( django.contrib.staticfiles.storage.HashedFilesMixin.patterns ) cover:
For example, the 'css/styles.css' file with this content:
…would be replaced by calling the url() method of the ManifestStaticFilesStorage storage backend, ultimately saving a 'css/styles.55e7cbb9ba48.css' file with the following content:
You can change the location of the manifest file by using a custom ManifestStaticFilesStorage subclass that sets the manifest_storage argument. For example:
Support for finding paths in the source map comments was added.
The manifest_storage argument was added.
Since static files might reference other static files that need to have their paths replaced, multiple passes of replacing paths may be needed until the file hashes converge. To prevent an infinite loop due to hashes not converging (for example, if 'foo.css' references 'bar.css' which references 'foo.css' ) there is a maximum number of passes before post-processing is abandoned. In cases with a large number of references, a higher number of passes might be needed. Increase the maximum number of passes by subclassing ManifestStaticFilesStorage and setting the max_post_process_passes attribute. It defaults to 5.
To enable the ManifestStaticFilesStorage you have to make sure the following requirements are met:
Since creating the MD5 hash can be a performance burden to your website during runtime, staticfiles will automatically store the mapping with hashed names for all processed files in a file called staticfiles.json . This happens once when you run the collectstatic management command.
If a file isn’t found in the staticfiles.json manifest at runtime, a ValueError is raised. This behavior can be disabled by subclassing ManifestStaticFilesStorage and setting the manifest_strict attribute to False – nonexistent paths will remain unchanged.
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.staticfiles.storage.StaticFilesStorage' (the default).
storage.ManifestStaticFilesStorage. file_hash (name, content=None)¶
The method that is used when creating the hashed name of a file. Needs to return a hash for the given file name and content. By default it calculates a MD5 hash from the content’s chunks as mentioned above. Feel free to override this method to use your own hashing algorithm.
Настройка статики¶
Убедитесь что django.contrib.staticfiles добавлено INSTALLED_APPS .
В настройках укажите STATIC_URL , например:
В шаблоне или “захардкодьте” URL /static/my_app/myexample.jpg , или лучше использовать тег static для генерация URL-а по указанному относительному пути с использованием бекенда, указанного в STATICFILES_STORAGE (это позволяет легко перенести статические файлы на CDN).
Сохраните статические файлы в каталоге static вашего приложения. Например my_app/static/my_app/myimage.jpg .
Serving the files
Кроме конфигурации, необходимо настроить раздачу статических файлов.
Потому что это представление очень неэффективно и, возможно, небезопасно. Оно предназначено только для разработки, и не должно использоваться на боевом сервере.
Способы раздачи статических файлов описаны в разделе Развертывание статических файлов.
Ваш проект, возможно, будет содержать статические файлы, которые не относятся ни к одному из приложений. Настройка STATICFILES_DIRS указывает каталоги, которые проверяются на наличие статических файлов. По умолчанию эта настройка пустая. Например:
Смотрите описание настройки STATICFILES_FINDERS чтобы узнать, как staticfiles находит файлы.
Static file namespacing
Вы можете добавлять статические файлы непосредственно в каталог my_app/static/ (не создавая подкаталог my_app ), но это плохая идея. Django использует первый найденный по имени файл и, если у вас есть файлы с одинаковым названием в разных приложениях, Django не сможет использовать оба. Необходимо как-то указать, какой файл использовать, и самый простой способ – это пространство имен. Просто положите их в каталог с названием приложения( my_app/static/my_app ).
Создание файла стилей css
Создайте файл «stylesheet.css» в static > css . Там будут храниться все ваши стили.
StaticFilesStorage ¶
A subclass of the FileSystemStorage storage backend that uses the STATIC_ROOT setting as the base file system location and the STATIC_URL setting respectively as the base URL.
storage.StaticFilesStorage. post_process (paths, **options)¶
If this method is defined on a storage, it’s called by the collectstatic management command after each run and gets passed the local storages and paths of found files as a dictionary, as well as the command line options. It yields tuples of three values: original_path, processed_path, processed . The path values are strings and processed is a boolean indicating whether or not the value was post-processed, or an exception if post-processing failed.
The ManifestStaticFilesStorage uses this behind the scenes to replace the paths with their hashed counterparts and update the cache appropriately.
Finders Module¶
staticfiles finders has a searched_locations attribute which is a list of directory paths in which the finders searched. Example usage:
5. Создание папки и файла JavaScript
Если нужно добавить кастомные JS-файлы в проект, создайте папку «js» внутри «static».
Можно также использовать элемент внутри шаблона, но создание отдельного JS-файла улучшит организацию проекта и поможет проще находить все скрипты в одном месте.
Использование тега static в шаблоне
После этого вы можете использовать тег «static» в шаблоне для работы с источником изображения.
dstatic > templates > home.html
Стоит отметить, что этот файл использует также Bootstrap CDN. Результат:
Storages¶
Раздача файлов, загруженных пользователем, при разработке¶
При разработке медиа файлы из MEDIA_ROOT можно раздавать используя представление django.contrib.staticfiles.views.serve() .
Не используйте его на боевом сервере! Способы раздачи статических файлов описаны в разделе Развертывание статических файлов.
Например, если MEDIA_URL равна /media/ , вы можете добавить следующий код в urls.py :
Serving static files during development¶
If you use django.contrib.staticfiles as explained above, runserver will do this automatically when DEBUG is set to True . If you don’t have django.contrib.staticfiles in INSTALLED_APPS , you can still manually serve static files using the django.views.static.serve() view.
This is not suitable for production use! For some common deployment strategies, see How to deploy static files .
For example, if your STATIC_URL is defined as static/ , you can do this by adding the following snippet to your urls.py:
Also this helper function only serves the actual STATIC_ROOT folder; it doesn’t perform static files discovery like django.contrib.staticfiles .
Finally, static files are served via a wrapper at the WSGI application layer. As a consequence, static files requests do not pass through the normal middleware chain .
7. Создание папки и файла для CSS
Также можно подключить CSS-файлы. Для этого создайте папку «css» внутри «static». Вы также можете использовать элемент и вложить все стили туда.
Но в случае создания отдельных классовых атрибутов, которые затем используются в разных шаблонах, лучше создавать отдельные папки и файлы.
Читайте также: