Configuring and connecting static files in Django

by Alex
Configuring and connecting static files in Django

If you’ve been looking for a way to add images, styles, and js to your Django project, you’ve come to the right place.

What are static files in Django? Images, JS and CSS files are called static files or Django project assets.

Code from the tutorial: https://gitlab.com/PythonRu/django_static

1. Let’s create a folder for static files

In the Django project folder, create a new “static” folder. In the example above it is in the “dstatic” directory. Создадим папку для статических файлов

2. Specify a static Django URL in the settings

Now make sure that Django django.contrib.staticfiles is listed in the list of installed applications in settings.py.

# dstatic > dstatic > settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

They should be there by default. After that, scroll to the bottom of the settings file and specify a static URL if it doesn’t already exist. You can also specify a static folder so Django knows where to look for static files.

# dstatic > dstatic > settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]

Remember to import the os library after adding the code above. Once the basic setup is complete, let’s look at how to add and show images in templates, as well as how to plug in your JavaScript and CSS files.

3. Create a folder for images

Create a folder in “static” specifically for images. Name it “img”. The main thing after that correctly refer to it in templates. Создайте папку для изображений

4. Load a static file into your HTML template

Now in the chosen template (for example, in “home.html”) load a static file at the top of the page. Загрузите статический файл в свой HTML-шаблон It is important to add {% load static %} before adding the image. Otherwise it will not be loaded.

Using the static tag in a template

You can then use the “static” tag in the template to work with the image source. dstatic > templates > home.html

{% load static %}
Home
Hi Django

It’s worth noting that this file also uses the Bootstrap CDN. Result: Настройка и подключение статических файлов в Django

5. Creating a JavaScript folder and file

If you want to add custom JS files to the project, create a “js” folder inside “static”. You can also use element inside the template, but creating a separate JS file will improve project organization and help find all the scripts in one place more easily.

Creating a script.js file

In the static > js folder, create a “script.js” file that stores all the JavaScript functions.

$(window).scroll(function() {
if ($(document).scrollTop() > 600 && $("#myModal").attr("displayed") === "false") {
$('#myModal').modal('show');
$("#myModal").attr("displayed", "true");
}
});

6. Load the script into the template

Now add the file in “header.html” to connect the JS file to the project. The file should be called in the same way as in the case of images. Don’t forget about {% load static %} at the top of the page for the tags to work properly.

{% load static %}
Home
Hi Django

7. Creating a folder and file for CSS

You can also include CSS files. To do this, create a “css” folder inside “static”. You can also use the element and put all the styles there. Создание папки и файла для CSS But in the case of creating separate class attributes that are then used in different templates, it’s better to create separate folders and files.

Creating a css stylesheet file

Create a “stylesheet.css” file in static > css. This will store all your styles.

.custom {
color:#007bff;
background:#000000;
font-size:20px;
}

8. Load a link to the CSS in the template

To connect your own styles to your project, add an HTML element to “header.html. The file is called in the same way as images and JS files.

{% load static %}
Home
Hi Django

Again, don’t forget the {% load static %} at the top of the page. If you don’t add this line there will be an error. If you add the custom class to the container you will see changes: Загрузите ссылку на CSS в шаблон

Errors related to loading static Django files

If you get the error “Invalid block tag on line 8: ‘static’, expected ‘endblock’. Did you forget to register or load this tag?”, you probably forgot to add a load static tag at the top of the page: {% load static %} before calling the image itself.

{% load static %}

This error “Could not parse the remainder: ‘/photo.jpg’ from ‘img/photo.jpg'” means that you forgot to add quotation marks around the image link. In this case, you need to use two pairs of quotes: one for the entire src content and one for the image reference.

 {# error #}
 {# right #}

“Invalid block tag on line 9: ‘static/img/photo.jpg’, expected ‘endblock’. Did you forget to register or load this tag?” indicates that you accidentally added a static tag to the URL.

 {# error #}
 {# right #}

If the page doesn’t load and the following error appears: “django.core.exceptions.ImproperlyConfigured: You’re using the staticfiles app without having set the required STATIC_URL setting”, it indicates that you forgot to specify the static URL in the settings file. You need to set it in settings.py and save the document.

STATIC_URL = '/static/'

Finally, if you don’t get the error, but the image doesn’t display, then make sure you are using the right tag.

 {# error #}
 {# right #}

Related Posts

LEAVE A COMMENT