56

I'm running Django's development server (runserver) on my local machine (Mac OS X) and cannot get the CSS files to load.

Here are the relevant entries in settings.py:

STATIC_ROOT = '/Users/username/Projects/mysite/static/'

STATIC_URL = '/static/'

STATICFILES_DIRS = (
'/Users/thaymore/Projects/mysite/cal/static',
)

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

INSTALLED_APPS = (
# other apps ...
'django.contrib.staticfiles',
)

In my views.py I'm requesting the context:

return render_to_response("cal/main.html",dict(entries=entries),context_instance=RequestContext(request))

And in my template the {{ STATIC_URL }} renders correctly:

<link type="text/css" href="{{ STATIC_URL }}css/main.css" />

Turns into:

<link type="text/css" href="/static/css/main.css"/>

Which is where the file is actually located. I also ran collectstatic to make sure all the files were collected.

I also have the following lines in my urls.py:

from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns += staticfiles_urlpatterns()

I'm new to Django so am probably missing something simple -- would appreciate any help.

tchaymore
  • 3,728
  • 13
  • 55
  • 86

21 Answers21

93

Read this carefully: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/

Is django.contrib.staticfiles in your INSTALLED_APPS in settings.py?

Is DEBUG=False? If so, you need to call runserver with the --insecure parameter:

python manage.py runserver --insecure

collectstatic has no bearing on serving files via the development server. It is for collecting the static files in one location STATIC_ROOT for your web server to find them. In fact, running collectstatic with your STATIC_ROOT set to a path in STATICFILES_DIRS is a bad idea. You should double-check to make sure your CSS files even exist now.

Andreas Bergström
  • 13,891
  • 5
  • 59
  • 53
GDorn
  • 8,511
  • 6
  • 38
  • 37
  • 4
    Yes, `django.contrib.staticfiles` is in INSTALLED_APPS (I edited question above), and DEBUG = True, and I've started server with --insecure parameter, but no luck. – tchaymore Sep 27 '11 at 20:00
  • 2
    Try loading one of the static urls directly. Is it a 404 or a 500? – GDorn Sep 27 '11 at 20:03
  • 2
    Yes, I can navigate to the css directly: http://127.0.0.1:8000/static/css/main.css/. Loads just fine. – tchaymore Sep 27 '11 at 20:19
  • Well, it's working now. Not sure what happened, but I'll give you the check. – tchaymore Sep 27 '11 at 20:21
  • 4
    Watch the output from runserver when you load the full page. There should be a request for /static/css/main.css and it should have a status code of 200. – GDorn Sep 27 '11 at 20:24
  • 1
    I'm guessing that your browser cached an older, possibly blank, copy of the CSS file, and navigating to it directly forced the browser to reload it. – GDorn Sep 27 '11 at 20:35
  • 1
    I think you mean `--insecure` is required if DEBUG=False ;) – Alasdair Sep 27 '11 at 20:43
  • 7
    I have the same problem and I get 404 not found. what can I do? – Alireza Farahani Dec 23 '13 at 19:53
  • Thank you. I had no idea about the --insecure parameter. – Alex Daro Jun 25 '17 at 22:40
  • 1
    @GDorn What is the correct practice in production, without using "--insecure"? – Rexcirus Jun 28 '19 at 00:07
  • 1
    @Rexcirus Don't use runserver in production. It's not made for that. Use gunicorn, mod_wsgi on apache, or uwsgi. Also avoid serving static assets via python at all if you can help it - use a webserver for that. If you absolutely must serve via python, use a library specifically for that purpose, such as whitenoise. – GDorn Jun 29 '19 at 23:46
37

For recent releases of Django, You have to configure static files in settings.py as,

STATIC_URL = '/static/' # the path in url

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

and use it with static template tag,

{% load static %}
<link rel="stylesheet" href="{% static 'css/bootstrap.css' %}">
All Іѕ Vаиітy
  • 24,861
  • 16
  • 87
  • 111
8

Another simple thing to try is to stop, and then restart the server e.g.

$ python manage.py runserver

I looked into the other answers, but restarting the server worked for me.

ibowman
  • 81
  • 1
  • 4
3

added

PROJECT_ROOT = os.path.normpath(os.path.dirname(__file__))
STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, "static"), )

and removed STATIC_ROOT from settings.py, It worked for me

Alan Francis
  • 1,249
  • 11
  • 17
Vinner
  • 1,231
  • 1
  • 15
  • 16
3

Add the following code to your settings.py:

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

After that, create the static folder at the root directory of your project.

To load the static files on templates use:

{% load static %}
  <img src="{% static "images/index.jpeg" %}" alt="My image"/>
SiHa
  • 7,830
  • 13
  • 34
  • 43
Alan Paul
  • 139
  • 1
  • 4
3

Are these missing from your settings.py? I am pasting one of my project's settings:

TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages")

Also, this is what I have in my urls.py:

urlpatterns += patterns('', (
        r'^static/(?P<path>.*)$',
        'django.views.static.serve',
        {'document_root': 'static'}
))
Geo
  • 93,257
  • 117
  • 344
  • 520
  • This worked. The django server cannot find and serve the static files in my local environment without serving them through a URL. adding this url pattern allowed the server to find and serve the file that lives in a directory in the project. I then added {{STATIC_URL}} and the file path - that lives in my app directory/static/appname/css/sass folder. I'm actually using this together with amazon s3 that I use in production, but need to alter the css in a local environment and have the static version displayed before pushing to the server with collectstatic. – CosmoRied May 05 '17 at 03:46
2

DEBUG = True in my local settings did it for me.

webjay
  • 5,358
  • 9
  • 45
  • 62
  • 2
    And what if we need to run server in production? – Viktor Sep 01 '16 at 13:28
  • Then you'd want to use `DEBUG = False` – AdamY Apr 25 '17 at 15:06
  • Don't use runserver in production. It's not made for that. It's not hardened, it's single-threaded, it's inefficient. Use a proper appserver, like gunicorn, uwsgi, or mod_wsgi, and serve your static assets from a proper webserver. – GDorn Jun 29 '19 at 23:50
2

These steps work for me, just see Load Static Files (CSS, JS, & Images) in Django

I use Django 1.10.

  1. create a folder static on the same level of settings.py, my settings.py's path is ~/djcode/mysite/mysite/settings.py, so this dir is ~/djcode/mysite/mysite/static/;
  2. create two folders static_dirs and static_root in static, that's ~/djcode/mysite/mysite/static/static_dirs/ and ~/djcode/mysite/mysite/static/static_root/;
  3. write settings.py like this:

    # Static files (CSS, JavaScript, Images)
    
    # https://docs.djangoproject.com/en/1.10/howto/static-files/
    
    STATIC_URL = '/static/'
    
    STATIC_ROOT = os.path.join(BASE_DIR, 'mysite', 'static', 'static_root')
    
    STATICFILES_DIRS = (
        os.path.join(BASE_DIR, 'mysite', 'static', 'static_dirs'),
    )
    
  4. do this command $ python manage.py collectstatic in shell;

  5. create a folder css in static_dirs and put into your own .css file, your css file' path is ~/djcode/mysite/mysite/static/static_dirs/css/my_style.css;

  6. change <link> tag in .html file: <link rel="stylesheet" type="text/css" href="{% static 'css/my_style.css' %}">,

Finally this link's path is http://192.168.1.100:8023/static/css/my_style.css

Bingo!

Belter
  • 3,573
  • 5
  • 42
  • 58
0

You had same path in STATICFILES_DIRS AND STATIC_ROOT, I ran into the same issue and below was the exception -

ImproperlyConfigured: The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting

For local you don't need STATICFILES_DIRS, as anyway you don't need to run collectstatic. Once you comment it, it should work fine.

Mutant
  • 3,663
  • 4
  • 33
  • 53
0

Have you added into your templates:

{% load staticfiles %}

This loads what's needed, but for some reason I have experienced that sometimes work without this... ???

viridis
  • 177
  • 10
0

I tried this model and it worked.

Changes in settings as per the django project created with shell

"django-admin.py startproject xxx"# here xxx is my app name

modify the folder as below structure loading our static files to run on server

Structure of xxx is:

>     .
>     |-- manage.py
>     |-- templates
>     |   `-- home.html
>     `-- test_project
>         |-- __init__.py
>         |-- settings.py
>         |-- static
>         |   |-- images
>         |   |   `-- 01.jpg
>         |   |-- style.css
>         |-- urls.py
>         `-- wsgi.py

- modifications in Settings.py

import os
INSTALLED_APPS = (    'xxx',# my app is to be load into it)

STATIC_ROOT = ''
STATIC_URL = '/static/'
PROJECT_DIR = os.path.dirname(__file__)
TEMPLATE_DIRS = (      os.path.join(PROJECT_DIR, '../templates'),)#include this 

- modifications in urls.py

from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView

class DirectTemplateView(TemplateView):
    extra_context = None
    def get_context_data(self, **kwargs):
        context = super(self.__class__, self).get_context_data(**kwargs)
        if self.extra_context is not None:
            for key, value in self.extra_context.items():
                if callable(value):
                    context[key] = value()
                else:
                    context[key] = value
        return context

urlpatterns = patterns('', 
    url(r'^$', DirectTemplateView.as_view(template_name="home.html")), )

- home.html

<html>
    <head>
        <link href="{{STATIC_URL}}style.css" rel="stylesheet" type="text/css">
    </head>
    <body>
        <h1>This is home for some_app</h1>
      <img src="{{STATIC_URL}}/images/01.jpg" width=150px;height=150px; alt="Smiley ">
    </body>
</html>
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
ayu for u
  • 197
  • 1
  • 4
0

I had to use

STATICFILES_DIRS = ( '/home/USERNAME/webapps/django/PROJECT/static/', )

That helped me.

jwebuser
  • 103
  • 1
  • 3
0

See if your main application (where the static directory is located) is included in your INSTALLED_APPS.

Files are searched by using the enabled finders. The default is to look in all locations defined in STATICFILES_DIRS and in the 'static' directory of apps specified by the INSTALLED_APPS setting.

Guy de Carufel
  • 466
  • 4
  • 8
0

Add this "django.core.context_processors.static", context processor in your settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.static",

)

cjahangir
  • 1,773
  • 18
  • 27
0

You can just set STATIC_ROOT depending on whether you are running on your localhost or on your server. To identify that, refer to this post.

And you can rewrite you STATIC_ROOT configuration as:

import sys

if 'runserver' in sys.argv:
    STATIC_ROOT = ''
else:
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
0

If you set DEBUG=FALSE you need to do follow steps

In your urls.py file: add this line

from django.views.static import serve

url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),

Thusitha Deepal
  • 1,392
  • 12
  • 19
0

I have the same issue (ununtu 16.04 server).

This helped me

python manage.py collectstatic --noinput

alcoder
  • 437
  • 4
  • 21
0

add following in settings.py

STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')  
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Amandeep Singh
  • 503
  • 3
  • 5
0

Two most Basis points to be noted for running Static files in Django Application are - Declare static file path in your settings.py file

STATIC_URL = '/static/'

Another important parameter is the web page in which you are using static keyword, you need to load the static files.

{% load static %}
help-info.de
  • 6,695
  • 16
  • 39
  • 41
0

Go to your HTML page load static by

{% load static %}

Now only mistake I've made was this

My code:

<img src="**{% static** "images/index.jpeg" %}" alt="My image">

Updated:

<img src=**"{% static 'images/index.jpeg' %}' alt="My image"**>

You get it right

DCCoder
  • 1,587
  • 4
  • 16
  • 29
  • 3
    This was [answered nine years ago by @GDorn](https://stackoverflow.com/a/7574901/3025856). That answer was not only accepted, but has also been validated by the community. Since then, eighteen other people have contributed additional answers—including another [highly rated answer from @all-Іѕ-vаиітy](https://stackoverflow.com/a/45918723/3025856) which references the same syntax. What does your answer contribute to the conversation? Why might someone prefer this approach over other approaches discussed? Please edit your answer to help readers understand why this is different. – Jeremy Caney Sep 27 '20 at 20:59
0

I had same issue check your settings.py and make sure STATIC_URL = '/static/' in my case first / at the beginning was missing and that was causing all static files not to work

badger
  • 1