Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django CSS Site Wide Static Files

Tags:

css

django

I am struggling to get css to work globally across my Django project.

I have a STATICFILES_DIRS called 'project_static' with a css file in it. This is in the root of my project. In my settings.py I have:

STATICFILES_DIRS = (
'/Users/gavinhinfey/django_projects/ss_stream/project_static/',
)

In base.html I have:

<link rel="stylesheet" href="{{STATIC_URL}}css/main.css">

{% block content %}
{% endblock content %}

The css file links fine when I'm at a page template within an app 'stream' which I have created. However when I'm viewing a page template not specific to an app it does not see the css.

Any idea why this is?

I've done my best to explain this but if you need clarification on the problem please ask.

Thanks Gavin

like image 895
Gavin Hinfey Avatar asked Oct 04 '22 06:10

Gavin Hinfey


1 Answers

{{STATIC_URL}} has been deprecated (I think) so it's probably rendering css/main.css only.

I suggest you configure it as follows:

settings.py

import os.path

PWD = os.path.dirname(os.path.realpath(__file__))  # project root path

STATICFILES_DIRS = (
    PWD + '/static/',  # or project_static, whatever
)

base.html

{% load static %}

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

This way you can use relative paths in your settings, and avoid breaking the settings if you move your whole project outside of your home directory.

You can use it for every path setting, such as LOCALE_PATHS or TEMPLATE_DIRS.

If this doesn't work yet check that you have these settings:

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    # 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# optional but if you defined it be sure to have this one:
TEMPLATE_CONTEXT_PROCESSORS = (
    # ...
    'django.core.context_processors.static',
    # ...
)
like image 106
Adrián Avatar answered Oct 07 '22 20:10

Adrián