Как подключить статику в django
При создании проекта Django он уже имеет некоторую базовую настройку для работы со статическими файлами. В частности, в файле settings.py определена переменная STATIC_URL , которая хранит путь к каталогу со статическими файлами:
А среди установленных приложений в переменной INSTALLED_APPS указано приложение django.contrib.staticfiles
Переменная STATIC_URL имеет значение «static/», а это значит, что нам достаточно создать в папке приложения каталог с именем «static» и добавить в него необходимые нам статические файлы. Но, естественно, при необходимости через данную настройку мы можем изменить расположение каталога статических файлов.
Итак, добавим в папку приложения новый каталог static . Чтобы не сваливать все статические файлы в кучу, определим для каждого типа файлов отдельные папки. В частности, создадим в папке static для изображений каталог images , а для стилей — каталог css . Подобным образом можно создавать папки и для других типов файлов.
В папку static/images добавим какое-нибудь изображение — в моем случае это будет файл forest.jpg . А в папке static/css определим новый файл styles.css , который будет иметь какие-нибудь простейшие стили, например:
Теперь используем эти файлы в шаблоне. Для этого в начале файла шаблона необходимо определить инструкцию
Django Basics: Static Files
What are Static Files?
Static files as the name suggests are the files that don’t change, your style sheets(css/scss) are not gonna change for every request from the client side, though the template might be dynamic. Also your logo, images in the design will not change unless you re-design it XD So these are the static files that needs to be rendered along with the templates.
You can learn about the theoretical information on static files from the django documentation.
How to configure Static Files
Firstly you can create a folder for all the static files in the root folder. Usually the convention is static as the name of the folder. So, if you have created the template folder in the root directory, similar to that static folder can be created in that path.
Next after creating the static folder in the project root folder, we need to configure the settings.py file to actually tell Django web server to look for all our static files in that folder. To do that, go to the settings.py file, now by this time you would have known where the settings.py file is (inside the project-named folder). Add the following at the end of the settings.py file.
Ignore the import os if you already have imported and the STATIC_URL if already there in the file. The STATICFILES_DIRS is the configuration that we tell the django environment to look for all our static files in the base/root directory of the project where the static/ folder is. The os.path.join() actually gets the path of the directory in our operating system to the folder specified in the case of our project the BASE_DIR is the path of the project and we add in the static folder to actually the project path. The final piece and the crucial one is the «static/» path, this can be other location where you have created your static folder within the project.
That’s it! Yes, it’s that simple. We can now create static files and render them in our templates.
Creating and Storing Static files
Now this part is customizable and it depends on your preference, how you want to organize the static folder. The convention that I follow is creating separate folders namely for css , js and assets (or img ) mostly. And inside of this folders you can store the respective static files. This also creates the project more scalable in terms of it’s maintenance.
Let’s create a static file and an image to demonstrate the concept of static files in django.
Demo Image (that’s my blog icon)
Rendering Static Files from Templates
So, after configuring and creating the static files, we now can inject them into our templates. If you try to do the traditional way i.e. linking stylesheets/images/script files with HTML, it just won’t work as you expect to and there’s no point in using traditional way while creating a web application with a framework. So, there is a framework specific way to do things which make it easier and efficient for the project.
To render any static file, we need to load the static tag which allows us to embed links for the static files into the templates. This means if the static files are not loaded directly instead in production(deploying our application) the static files are stored in a folder STATIC_ROOT which the server then loads, we’ll see how that internally works when we get to deployment techniques for Django project.
To load the static files from our configuration, we can simpy include the tag on top of the template.
The above templating tag will load the static tag which allows us to embed the links to the static files as explained earlier.
Now, we can actually access any file with the static folder in our templates with a particular syntax as below:
NOTE: The path to the static file is relative from the Static folder, i.e. enter the path of the file considering the static folder as the base directory.
Demonstration of the static file
Let’s render the static file which we created earlier i.e. the css file and the image into a template.
Assuming you have a app called post in your django project, you can render static files as below:
Append the following if your templates and static files are not configured properly.
This will also work if you do it with traditional HTML syntax, but I’d explained why it’s not recommended to do it while using frameworks.
Let’s see how static files are rendered in inherited templates. We’ll tinker with the for.html template created in the previous part .
So, that’s the url and view map created, we can now be able to see the result in the 127.0.0.1:8000/for/ url to see the below result:
The list style has been changed and thus we can see that the CSS from the parent template is also being inherited.
Here is the django project structure which I have created with this series so far:
So that has been it for the Static files in Django. Though there are lot of depth for rendering and loading the static files, we’ll explore as we get our grasp in the django and web development terminologies.
Hope you found it helpful and if you have any queries please let me know. We’ll start with the databases probably from the next part in the Django Basics Series. Until then have a great week and as always Happy Coding 🙂
This page describes how you can serve these static files.
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 STORAGES alias.
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 .
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 :
This helper function works only in debug mode and only if the given prefix is local (e.g. static/ ) and not a URL (e.g. http://static.example.com/ ).
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 .
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 :
This helper function works only in debug mode and only if the given prefix is local (e.g. media/ ) and not a URL (e.g. http://media.example.com/ ).
When running tests that use actual HTTP requests instead of the built-in testing client (i.e. when using the built-in LiveServerTestCase ) the static assets need to be served along the rest of the content so the test environment reproduces the real one as faithfully as possible, but LiveServerTestCase has only very basic static file-serving functionality: It doesn’t know about the finders feature of the staticfiles application and assumes the static content has already been collected under STATIC_ROOT .
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.
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.
Django Static Files and Templates
For local development the Django web server automatically serves static files and minimal configuration is required. A single Django project often contains multiple apps and by default Django will look within each app for a static directory containing static files.
For example, if one of your apps was called blog and you wanted to add a CSS file to it called base.css , you would need to first create a new directory called blog/static and then add the file within it at the location blog/static/style.css .
However, since most Django projects involve multiple apps and shared static files, it is common on larger projects to instead create a base-level folder typically named static . This can be added from the command line with the mkdir command:
For demonstration purposes let’s also add a base.css file. Assuming you had only just started a new Django project with the startproject command your directory structure would now look like this:
Within the settings.py file, near the bottom, there is a single line of configuration for static files called STATIC_URL, which is the location of static files in our project.
This means that all static files will be stored in the location http://127.0.0.1:8000/static/ or http://localhost:8000/static/ . And if you wanted to access the base.css file its location would be http://127.0.0.1:8000/static/base.css or http://localhost:8000/static/base.css .
Loading static files into Templates
Loading static files in a template is a two-step process:
- add <% load static %>at the top of the template
- add the template tag with the proper link
There are two main ways to structure templates in a Django project as outlined in this tutorial. Let’s assume we are using a templates/base.html file for a Blog project. To add our static base.css file to it we’d start by adding <% load static %>at the top of the file and then use the <% static %>tag with the path to it. Since the STATIC_URL is already set to /static/ we don’t need to write the full route out of static/base.css and can instead shorten it to base.css .
Serving static files in production requires several additional steps and is where the confusion typically arises for Django newcomers. Local development is designed to keep things nice and easy, but it is far from performant. In a production environment it is more efficient to combine all static files in the Django project into one location and serve that a single time.
Django comes with a built-in management command, collectstatic, that does this for us.
We need three more configurations in our settings.py file though before collectstatic will work properly. The first is STATICFILES_DIRS which defines additional locations, if any, the staticfiles app should look within when running collectstatic . In our simple example the only location for local files is the static directory so we will set that now.
Next up is STATIC_ROOT which sets the absolute location of these collected files, typically called staticfiles . In other words, when collecstatic is run locally it will combine all available static files, as defined by STATICFILES_DIRS and place them within a directory called staticfiles . This is how we set that configuration.
The final step is STATICFILES_STORAGE, which is the file storage engine used when collecting static files with the collectstatic command. By default, it is implicitly set to django.contrib.staticfiles.storage.StaticFilesStorage . Let’s make that explicit for now in our django_project/settings.py file.
Now we can run the command python manage.py collectstatic which will create a new staticfiles directory.
If you look within it you’ll see that staticfiles also has folders for admin (the built-in admin has its own static files), staticfiles.json , and whatever directories are in your static folder.
If you now add a new static file to the static directory it will immediately be available for local usage. It is only for production where the file won’t be present unless you run python manage.py collectstatic each and every time. For this reason, running collectstatic is typically added to deployment pipelines and is done by default on Heroku.
As a brief recap:
- STATIC_URL is the URL location of static files located in STATIC_ROOT
- STATICFILES_DIRS tells Django where to look for static files in a Django project, such as a top-level static folder
- STATIC_ROOT is the folder location of static files when collectstatic is run
- STATICFILES_STORAGE is the file storage engine used when collecting static files with the collectstatic command.
Even though we’ve configured our Django project to collect static files properly, there’s one more step involved which is not included in the official Django docs. That is the configuration of WhiteNoise to serve the static files in production. The first step is to install the latest version of the package:
Then in the django_project/settings.py file make three changes:
- add whitenoise to the INSTALLED_APPS above the built-in staticfiles app
- under MIDDLEWARE , add a new WhiteNoiseMiddleware on the third line
- change STATICFILES_STORAGE to use WhiteNoise .
It should look like the following:
That’s it! Run python manage.py collectstatic again so that the files are stored using WhiteNoise. And then deploy with confidence to the hosting platform of your choice.
Content Delivery Networks (CDNs) are useful on very high traffic sites where performance is a concern. Rather than serving static files from your Django server you post them on a dedicated CDN network and then call them. The official WhiteNoise documentation has additional instructions on this step.
Configuring static files is a core part of any Django project. If you’d like to see multiple examples of real-world Django projects alongside detailed explanation, check out my book Django For Beginners. The first several chapters can be read for free online.
© LearnDjango | Django is a registered trademark of the Django Software Foundation.