Adding css to django template

Add CSS and Static Files in Django | Is Your CSS Not Loading?

As a part of the Django tutorial series, we will learn to add CSS and other static files in Django. We will also see how you can debug if your static files are not properly loading in the Django template.

Setting Static URL in Django

Open setting file (settings.py) in your Django project and set STATIC_URL and STATICFILES_DIRS variables.

STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static/"), )

BASE_DIR is the path to the Django project files. It might be already defined in the settings.py. Otherwise, you can set it.

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

Now include django.contrib.staticfiles in the INSTALLED_APPS list in settings.py.

INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # newly added 'registration', 'myapp', ]

Make new directory named ‘static’ inside the project directory. And add all your static files including css, images and JavaScript.

Here we are adding css ‘style.css’ in the static directory. To make it more organized, we creating css as subdiectory inside static directory to add style.css.

Just like CSS, you can create the separate directory like ‘js’, ‘img’ to save JavaScript, Images in the static directory.

Here is the structure of the project directory after adding CSS.

├───myapp │ ├───migrations │ ├───templates ├───static │ └───css | └───style.css └───myproject ├───templates └───registration

Including CSS in Django Template

We need to load the static files by adding the below line of code at the top of the template (.HTML) file.

Then, insert the stylesheet in the HTML using link HTML tag.

If you are new to the HTML and CSS, you can learn more about adding CSS in HTML code.

You have done with all the settings.

Start your project by running below command.

python manage.py runserver

And open your project URL in the web browser.

You can see the your HTML template decorated with your style sheet.

Note: I tested this code and implementation in the Django 2.2 version and it is expected to work on any Django version.

Resolving 404 Not Found Error for Static Files

If your project is unable to locate the CSS or any other status files inside your project directory, it will throw HTTP 404 status code as an error.

Is your Django CSS not loading?

There are multiple ways of debugging it.

Using findstatic option

Run manage.py with find static option.

If Django project able tp locate the CSS, it will return path to your CSS file.

Читайте также:  Java select main class

$ python manage.py findstatic css/style.css Found ‘css/style.css’ here:

If the CSS static file not found, it will throw an err as “No matching file found”

$python manage.py findstatic css/style.css No matching file found for 'css/style.css'.

Using Browser Console Output

If you see your CSS or static files are not added properly, you can check the browser console output.

To see the console output in Google Chrome browser,

Django static CSS not found error in console

  • right-click on browser window
  • select “inspect” or press ”Ctrl+Shift+I”
  • open “Console” tab in “inspect”

You can see the error message.

GET http://127.0.0.1:8000/static/css/style.css net::ERR_ABORTED 404 (Not Found)

It has clearly mentioned that static file is not found.

There can be multiple reason if the Django is unable to loacte static files.

  • Check the static file directory and file names. I remember spending half an hour as I added .css explicitly in the file name and Django was reading this file as style.css.css.
  • Recheck all the static URLs and paths set in the settings.py

Understanding STATIC_ROOT and STATICFILES_DIRS

Don’t get confused with the STATIC_ROOT and STATICFILES_DIRS in settings.py.

When I faced the issue with my static, I dig into the internet. After reading through multiple pages, I found it more confusing. So, I just want to make it simple and clear for you.

Both of these paths have different use.

STATICFILES_DIRS

You can keep the static files in multiple directories. For example, you might want to keep one static file directory for each Django app. In this case, you can list down all the static file paths inside in STATICFILES_DIRS list.

STATIC_ROOT

If your project is under development, you don’t need to set STATIC_ROOT in Django settings. This path is used when you deploy your project.

When you run below command, it will collect all the static files into the STATIC_ROOT path directory.

python manage.py collectstatic --noinput

Keeping all the static files in one directory is useful to secure your files in production.

This is all about how to add CSS in Django. Similarly, you can add other static files like JavaScript, Images, etc. Let me know if you are facing any problem adding static files in your Django project.

Python Interview Questions eBook

Aniruddha Chaudhari

I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Comments

Ina

Hi, I am actually struggling with the fact that my background.png, no matter what I try, will not load on-site.
Here’s the situation : Music(app) – static- music- images(background.png) / style.css
Now, in style.css, I tried multiple solutions, see below, but none work:
I read about others having the same issue no matter what they tried.
The above article info doesn’t seem to apply to my situation. hmm body cover < background: url(‘/static/img/background.png’);>

background:url(‘../img/background.png’)
>
…………………………………………………………………………………………………………….
And with this occasion, allow me to ask about another interesting fact I came across and not yet manage to understand what it is, but I made it work by leaving empty the field wherein the tutorial was filled with:
href=”” index.html I put spaces coz it seems it won’t load the code when I publish the comment.

lt a href=" empty here " rel="nofollow ugc" gt lt /a gt

THE ERROR on site: NoReverseMatch at /music/
Reverse for ‘index’ not found. ‘index’ is not a valid view function or pattern name. I’d really appreciate your view.py or opinion.py regarding these matters 🙂
Nice site, btw. I just came across your site and the info looks recognizable(organized) by me, a beginner, which I guess is a good thing 🙂 Cheers and thanks,
Adina

Читайте также:  Energy report html file
Aniruddha Chaudhari

Hi Adina, I’m very glad you find our platform valuable for your learning. Regarding your query, I think you are not able to set the background image. This is more likely because you are trying to access the background.png image in the CSS file using the URL function which you cannot access there. Just to make sure, you check the source code of that page and see what URL is showing. Here is the probable solution to the problem. Instead of setting background image in CSS, set that in an HTML template file using inline CSS code.

Let me know if this works.
————- Regarding other findings… The information you provided is not sufficient to dig. What I can say is that check the url.py

path('index/', views.index, name='index'),
Adina

Hi,
THANK YOU so much for your reply. Regarding the background image, eventually, I managed to load an image directly from the internet, without using the saved image in /music/static/images.
If I remember well, in the HTML file, it doesn’t work to put the image. The code line would appear on the site’s top of page:)))))
So I have this : style.css body background: url(“https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTIKBRRyy_Hl60hXuxoq0PRS_Zhw8nyvCHRoA&usqp=CAU”)
>
…………………………………………………………………………………….
Now, regarding the index matter, I see it works this way, at least no error anymore, hihihi 😀 : music/urls.py urlpatterns = [
# /music/
path(” “, views.index, name=’index’), (no index between ” “, coz it’ll show error ) index.html

HTML a tag - href="index' %>" rel="nofollow ugc" - MusiCoded

(now it works with <% url ‘music:index’ %>,before it would work with href=’ ‘ ) What do you think? 🙂 I sensed it must have been related to urls.py and even looked to that line(just looked…:)) ), but I wasn’t sure, and coz I couldn’t find a clear answer I remained wrapped in mystery. Now I can continue my learning, even though this is learning too :))
I got myself hit by the ambition to learning to code even if I am self-taught and have studied music before. Maybe later, an internship, some more advanced courses. Pff 🙂 Any advice regarding the order of the information I should learn? I am asking because a course, for ex, follows a systematic curriculum, but being self-taught, sometimes it feels like swimming in an ocean of info I have to search, differentiate(for my needs). This can cut a bit the learning flow, but on the other hand, I am encouraged by the fact that my intuition seems to help me. Thank you so much, again. And keep in touch.
Have a nice time there Aniruddha:) PS Hopefully I didn’t bore you with this kilometric comment 🙂

Читайте также:  Install python django linux
Aniruddha Chaudhari

You’re welcome, Adina! I’m glad you find the solution to your background image problem. And hope it is solved now. Regarding, second matter, <% url ‘music:index’ %>is used to get the URL link. We can use this tag anywhere in the HTML template. href=” is the HTML attribute associated with HTML ‘a’ tag. Both serve a different purpose. Learn to code is all about the process. If you enjoy doing it, you will keep learning. I like your spirit. Be with that. You will find tones of information to learn and sometimes to get lost 😀 So you should have proper agenda and a planned out carriculum. I would like to help you but I’m not sure your purpose behind learning and what you want to accomplish. But as I see you are learning Django, learn some basic HTML and CSS tags (if you are not familiar with). We also have Python group on Facebook where we discuss different topics. No worries! We will be in touch through this blog 😀 Feel free to drag me if you stuck 😉 Take care and keep coding!

Источник

Настройка и подключение статических файлов в Django

Если вы искали способ добавить изображения, стили и js в свой проект на Django, то пришли по адресу.

Что такое статические файлы в Django?
Изображения, JS и CSS-файлы называются статическими файлами или ассетами проекта Django.

1. Создадим папку для статических файлов

В папке проекта Django создайте новую папку «static». В примере выше она находится в директории «dstatic».

Создадим папку для статических файлов

2. Укажите статический URL Django в настройках

Теперь убедитесь, что статические файлы Django django.contrib.staticfiles указаны в списке установленных приложений в 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', ]

Они должны быть там по умолчанию.

После этого пролистайте в нижнюю часть файла настроек и укажите статический URL, если такого еще нет. Вы также можете указать статическую папку, чтобы Django знал, где искать статические файлы.

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

Не забудьте импортировать библиотеку os после добавления кода выше.

После завершения базовой настройки рассмотрим, как добавлять и показывать изображения в шаблонах, а также как подключить свои JavaScript и CSS файлы.

3. Создайте папку для изображений

Создайте папку в «static» специально для изображений. Назовите ее «img». Главное после этого правильно ссылаться на нее в шаблонах.

Создайте папку для изображений

4. Загрузите статический файл в свой HTML-шаблон

Теперь в выбранном шаблоне (например, в «home.html») загрузите статический файл в верхней части страницы.

Загрузите статический файл в свой HTML-шаблон

Важно добавить до того, как добавлять изображение. В противном случае оно не будет загружено.

Использование тега static в шаблоне

После этого вы можете использовать тег «static» в шаблоне для работы с источником изображения.

dstatic > templates > home.html

Источник

Оцените статью