[Django]-Django not loading CSS?

5πŸ‘

βœ…

The problem comes from 2 areas.

  1. wrong document_root variable passed
  2. not using template tags in html

1.
Defining site_media variable in urls.py file is discouraged as it does not adhere to DRY principle. It should be held as a variable in your settings.py file so other modules may import if needed.
In your settings.py file, add the following line:

import os.path
SITE_MEDIA_ROOT = os.path.join(
    os.path.dirname(__file__), 'myApp/', 'static/', 'site_media' #this should be the correct path instead
)

Replace your urls.py file with this:

from myApp import settings

urlpatterns = patterns('',
url(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{ 'document_root': settings.SITE_MEDIA_ROOT }),
)

2.You should use django template tags to get the css file. In your base template, add this line above the head tag:

{% load static %}

Then replace:

<link rel='stylesheet' type='text/css' href='/site_media/css/style.css' />

with:

<link rel='stylesheet' type='text/css' href="{% static 'site_media/css/style.css' %}" />

After which it should work.

πŸ‘€hguochen

1πŸ‘

Two options:

  1. You can modify a little bit your code in urls.py

in urls.py

site_media = os.path.join(
    os.path.dirname(__file__), 'site_media'
)

to

site_media = os.path.join(
    os.path.dirname(__file__), "../", "myApp", "static", 'site_media'
)

2. Remove

site_media = os.path.join(
    os.path.dirname(__file__), 'site_media'
)

and add

{% load static %} at the beginning of base.html

and change

<link rel='stylesheet' type='text/css' href='/site_media/css/style.css' />

to

<link rel='stylesheet' type='text/css' href="{% static 'site_media/css/style.css' %}" />

The second method is preferable.
Here is working code: https://github.com/lukaszszajkowski/s21083672

Here are links to documentation and reading:
https://docs.djangoproject.com/en/dev/howto/static-files/#configuring-static-files
Media files are served, static files aren't

πŸ‘€fragles

Leave a comment