Reputation: 67
I just started learning django framework and i tried to add and use static files to design a template(to change the background) of webpage with simple css but my css file doesn't seem to link with html template as the background did not change.
I looked up various solutions and it doesn't seem i am doing anything wrong in the code but it still doesn't work. Please look at the code, what could i be missing?
Here is the code for the template;
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="music/style.css">
{% if all_albums %}
<h3>My Albums</h3>
<ul>
{% for album in all_albums %}
<li><a href="{% url 'music:detail' album.id %}">{{album.album_title}}</a></li>
{% endfor %}
</ul>
{% else %}
<h3>You don't have any albums</h3>
{% endif %}
Here is the css;
body{
background: white url("images/blackbackground.jpg");
}
I expected the background to change but it didn't. The server returned error message "Not Found: /music/music/style.css [01/Feb/2019 12:15:26] "GET /music/music/style.css HTTP/1.1" 404 2559" guys what am i missing?
Upvotes: 1
Views: 176
Reputation: 83
To make the static files work on Django you need to have a couple of variables in place.
First, in your settings.py
you'll have to have your static file variables set.
Here I show you an example of the one I use:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'staticfiles')
STATICFILES_DIRS = (
'static',
os.path.join(os.path.dirname(BASE_DIR), 'static')
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
This means that you will need to have a static folder in the same folder as your main app.
For example:
├── apps
│ ├── api
│ ├── blog
│ └── home
├── manage.py
├── media
│ ├── images
│ └── original_images
├── requirements
│ ├── base.txt
│ ├── development.txt
│ └── production.txt
├── src -----> THIS IS MY MAIN FOLDER
│ ├── __init__.py
│ ├── __pycache__
│ ├── db.sqlite3
│ ├── locale
│ ├── media
│ ├── settings ------> THIS IS MY SETTINGS FOLDER
│ ├── urls.py
│ └── wsgi.py
├── static ------> THIS IS MY STATIC FOLDER
│ ├── css
│ ├── figures
│ ├── fonts
│ ├── img
├── templates
│ └── base.html
└── utilities
Next, you'll need to add this to your main urls.py
:
from django.conf.urls.static import static
from django.conf import settings
# Serve static files with Django. Normally this is for development purposes.
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
After that, the last part goes into your templates, you'll need to load static template tags and use the following syntax:
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'music/style.css' %}">
At the end, it will render something like:
<link rel="stylesheet" type="text/css" href="/static/music/style.css">
Upvotes: 1