DougM
DougM

Reputation: 940

Django can't find static folder

I am looking to add a css file to Django but it can't find the static folder.

Here is my settings.py file:

"""
Django settings for opengarden project.

Generated by 'django-admin startproject' using Django 2.2.3.

For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '__________'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

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

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'opengarden.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'wx', 'templates'),],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'opengarden.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'America/Denver'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'

STATIC_ROOT = ''

My base html file:

<!DOCTYPE html>
<html lang="en">
<!DOCTYPE html>
<html lang="en">
<head>
    {% block title %}<title>Garden Dash</title>{% endblock %}
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    {% load static %}
    <link rel='stylesheet' href="{% static 'wx/css/styles.css' %}">
</head>
<body>
  <div class="container-fluid">
    <div class="nav">
        <ul>
            <li>Plants</li>
            <li>Weather</li>
            <li>Soil</li>
            <li>Yield</li>
        </ul>
    </div>
    <div class="row">
      <div class="col-sm-10">{% block content %}{% endblock %}</div>
    </div>
  </div>
</body>
</html>

My folder structure is as follows:

gardendash > wx > static > wx > css > styles.css

and my style sheet is simply,

html {
    background-color: black;
}

I searched through stack overflow and found a couple solutions but they didn't fix the issue. I also found one that said to type the following to find my static location

python manage.py findstatic --verbosity 2 css/style.css

the result I am receiving is

No matching file found for 'css/style.css'.

Looking in the following locations:
/home/my_name/.virtualenvs/django/lib/python3.6/site-packages/django/contrib/admin/static

Any suggestions as to what I am doing wrong? I have tried adjusting the root url in settings.py to the folder directory as well but no luck.

Thank you all for your time.

Upvotes: 5

Views: 7932

Answers (2)

xyres
xyres

Reputation: 21834

You mention that the structure of your project is like this:

project_folder > app > static > app_name > css > styles.css

Since styles.css is inside your app's static directory, you can't simply access this file as /static/css/styles.css. This is the wrong path.

The correct path is this: /static/app_name/css/styles.css.

So, in your template you'd access your file like this:

{% static 'app_name/css/styles.css' %}

Also, make sure the app is listed in INSTALLED_APPS.


Additionally, let me clarify a few things:

  1. STATIC_ROOT: This is the name of the directory where django will keep all the static files when you run manage.py collectstatic command. This is only required in production, otherwise this directory will and should be empty. The collectstatic command copies all static files from your apps and from your project.
  2. STATIC_URL: This is the url prefix that django uses to generate url paths for static files. If STATIC_URL is set to /static/, django will convert {% static 'file.jpg' %} to /static/file.jpg.
  3. STATICFILES_DIRS: This is a list containing paths to directories where you've kept your project specific static files. This is only required for development. When you run collectstatic command, Django will copy files from all the listed paths in this list and place them in the STATIC_ROOT.
  4. You don't need to configure any url to serve static files because django does that by default during development as long as django.contrib.staticfiles is in your INSTALLED_APPS.

Upvotes: 6

Fatema Tuz Zuhora
Fatema Tuz Zuhora

Reputation: 3756

I've solved a similar issue by following steps:

  1. Add the following line of codes inside settings.py
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = (
  os.path.join(BASE_DIR, 'static_root'),
)

STATIC_ROOT = os.path.join(BASE_DIR, 'static')
  1. Then create a folder named static_root inside my project folder, and insert there my custom stylesheet or scripts.
  2. Run the following command in my console:
python3 manage.py collectstatic

I am using python3 on Ubuntu, If you are a windows user the command will be python manage.py collectstatic

Then all the static files that I saved inside static_root folder, and other necessary static files from the project, all files will be automatically generated inside the static folder.

  1. Now inside my base HTML file add {% load static %}:

Here is the Example:

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <!-- meta tags -->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <!-- custom css -->
    <link rel="stylesheet" href="{% static 'css/styles.css' %}">

    <title>Django Project</title>
</head>

Upvotes: 2

Related Questions