Skip to content
Advertisement

Implementing CSS in Django

I’m trying to implement a simple CSS file to my python web app. When I try loding the app, I get a error message in the command prompt that says:

"GET /static/css/default.css HTTP/1.1" 404 1658

And of course no CSS is implemented to the HTML page. The structure of my Project is:

ProjectName
 MyApp
 MyTeachingApp
  static
   css
    default.css
 templates
  page.html

In my settings.py, I got:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
STATIC_URL = '/static/'

And in the html I got the link tag inside the head like:

<link rel="stylesheet" href="{% static "css/default.css" %}" />

How do I correctly implement the CSS in my web app? Do I’ve to add something to the url.py? Or is it in the settings.py using the STATIC_ROOT or STATICFILES_DIRS?

I’m using Django 1.9.

My urls.py file contains the following code:

    from django.conf.urls import url, include
from django.contrib import admin
from django.views import *
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^caesarTemp/', include('TeachingTool.urls')),
] + static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)

This is the urls.py inside the MyApp folder.

I have an extra urls.py file inside a MyTeachingApp folder that contains:

    from django.conf.urls import url
from . import views
urlpatterns = [
    url(r'^$', views.printAlphabet, name = 'print'),
]

I tried adding the static statement to this urls.py file and still didn’t work.

Advertisement

Answer

You need to add your app to INSTALLED_APPS tuple. Also, add the urlpatterns for serving static files with your local development server, like mastazi said:

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Your app is named MyTeachingApp so it seems; your INSTALLED APPS configuration should look like:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'MyTeachingApp',
]
Advertisement