109

I can't get my static files to come up. I've tried various settings and directory configurations and so on, but they just turn up as 404s. I have debug_toolbar installed so know that STATIC_URL is reaching my request context.

Directory structure showing /static (I have also placed the directory inside of the meals app folder, and users, just to try it out.

/mealmate
    /mealmate
    /meals
    /static
        /css
             /bootstrap.min.css
    /templates
    /users

Settings.py (a few important settings though I've experimented with a variety of other ones):

MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media/')

STATIC_URL = '/static/'

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

WSGI_APPLICATION = 'mealmate.wsgi.application'

In base.html rendered

    <link rel="stylesheet" href="/static/css/bootstrap.min.css">

Any ideas? Thanks

KindOfGuy
  • 3,081
  • 5
  • 31
  • 47
  • 8
    Why do I need to run collectstatic if I've manually produced a static folder? I did it anyway, but it still didn't work. Django is not recognising my static folder despite the settings. – KindOfGuy Oct 10 '12 at 22:08
  • 65
    Try: `python manage.py findstatic --verbosity 2 css/styles.css` to see where Django is looking for your static files. – deed02392 May 11 '16 at 09:31
  • 4
    @deed02392 I know this is a long time later but THANK YOU, I couldn't find out why mine wasn't working. No matter how much I tried to change `STATIC_URL` in my settings it wouldn't work. Then that command help me find the location, I don't know why it wouldn't change though – Amon Jul 05 '17 at 23:26
  • 1
    Glad it helped @Amon, it was the key command to help me figure out what was going on too – deed02392 Jul 07 '17 at 18:29
  • @deed02392. thank you now I know where Django is looking for my files. see because I'm using the Django-tailwind framework I should have a static root. and static root can't be contained in my STATICFILES_DIRS(Otherwise it returns an error). and tailwind CSS files are located in my static root. but Django doesn't look in the static root directory so I can't use tailwind files. Do You Have Any suggestions?? –  Aug 06 '22 at 16:50

28 Answers28

162

This is the working solution for static/media/template access in django for windows,

settings.py

STATIC_ROOT = ''

STATIC_URL = '/static/'

STATICFILES_DIRS = ('static',)
kaankutan
  • 91
  • 2
  • 9
Amar Kamthe
  • 2,524
  • 2
  • 15
  • 24
  • 4
    Thanks, great! For additional info you can follow http://blog.xjtian.com/post/52685286308/serving-static-files-in-django-more-complicated-than this blog, very practical description how to serve with static in django. – The Godfather Oct 10 '14 at 05:36
  • 12
    `os.path.join('static')` gives simple `'static'` – Sławomir Lenart Apr 27 '16 at 15:25
  • This helped me as well. To more specifically identify the problem in my case, I had a leading "/" in my join() string. – Matthew Weber Apr 07 '18 at 13:29
  • 1
    `STATIC_ROOT` specification is not required. And, as @SławomirLenart pointed out, you can get rid of the `join` and just use the string. – cirrusio Apr 26 '18 at 17:21
  • 3
    @cirrusio STATIC_ROOT is actually what was required for me. I was following the tutorial, and couldn't get static files to load. I simply added the line STATIC_ROOT = '' and it started working. I didn't need any other changes. – Jeffrey Harmon Oct 29 '18 at 20:58
  • @JeffreyHarmon both worked for me..i just added STATICFILES_DIR as specified & it worked, then i removed STATICFILES_DIR and added only STATIC_ROOT and this setting also worked. – ArigatoManga Feb 27 '19 at 13:08
  • Thanks, be nice if Django just done this out of the box! – Jack Vial Aug 21 '19 at 01:44
  • Thank you very much – Sanjeev Kumar Apr 06 '21 at 21:25
  • important to notice that during development you'll need to set DEBUG True in order to avoid serving the files https://docs.djangoproject.com/en/3.0/howto/static-files/ – RanH Jun 09 '21 at 12:40
83

For me this turned out to be caused by setting debug to false in settings.py. A workaround is to pass the --insecure switch to runserver, but the real solution is to use a proper web server to serve the static files. See the answers to this question for more details.

Community
  • 1
  • 1
Arthur Tacca
  • 8,833
  • 2
  • 31
  • 49
  • 5
    Dude. After hours of trying, this solved the issue. THANKS – М.Б. Oct 18 '19 at 16:26
  • 3
    THANKS++ I was turning crazy. – NiKo Mar 05 '20 at 09:07
  • 2
    This! Many thanks, went almost crazy debugging my static files... – jpdus Mar 21 '20 at 20:03
  • yyyuuup. that worked on a production server but one of my developers had problems on local runserver on windows.. turns out debug needs to be enabled locally :-) thank you! :-) – CeDeROM Sep 20 '20 at 19:50
  • 2
    How silly is this issue? After putting some changes into production and setting Debug = False my development environment suddenly stopped serving static files and it has taken my hours to find this solution. This should be documented somewhere or a clear warning given in the logs. – Rob Mascaro Feb 07 '21 at 03:47
  • This is so amazing. I had the issue because config file had trouble resolving the 'DEBUG' key and i had no hint what so ever. Zillion thanks. – xySVerma Mar 28 '21 at 20:53
26

If you are running this on a web server are you copying the static files to a public accessible folder? For example:

# web accessible folder
STATIC_ROOT = '/home/your_name/www/mealmate/static/'

# URL prefix for static files.
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    # location of your application, should not be public web accessible 
    '/home/your_name/website/mealmate/static',
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

Then you can use this post Django static Files and copy the static files to the public accessible folder using manage.py

# --link    Create a symbolic link to each file instead of copying.
# --noinput Do NOT prompt the user for input of any kind.
#
python manage.py collectstatic -link --noinput

Hope that helps!

Community
  • 1
  • 1
eodgooch
  • 1,322
  • 1
  • 11
  • 17
  • Are the URIs intentionally different? (`www` vs `website`)? – Rikki Nov 03 '16 at 00:33
  • @Rikki yes, to show that you can add additional static file directories. Django will bundle all files in those directories and copy to the `STATIC_ROOT` – eodgooch Nov 16 '16 at 17:33
17

from comments above - run this

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

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

Looking in the following locations:
/Users/yourname/Documents/Workspace/test/staticfiles

I simply renamed my static folder to staticfiles and all was well. (I'm on osx + django 1.x)

use insecure mode may not hurt if you're on local dev box - otherwise you may still get 404 errors.

python manage.py runserver --insecure

UPDATE

actually digging into settings.py found the infringing line.

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'staticfiles'),
)
johndpope
  • 5,035
  • 2
  • 41
  • 43
14

If you recently changed the debug to false in settings file. Follow this procedure.

Most of the time it is caused by debug setting to be false in settings.py. If you pass the --insecure switch to runserver it should work. So if you do python manage.py runserver 0.0.0.0:8000 change it to python manage.py runserver 0.0.0.0:8000 --insecure instead.

It should work.

Kunal Kumar
  • 1,139
  • 14
  • 13
  • 2
    From reading the docs I am taking that django will serve statics with dev mode on. On the other hand for dev mode off you should use nginx really, as serving statics by django is inefficient. The flag above means that you acknowledge that fact. – Adam Dec 20 '19 at 07:28
  • 2
    This error message should be a little more obvious, wasting time to search for the problem, thank you for your answer – Albert.Qing Jul 24 '22 at 23:46
9

I simply added the equivalent of

STATICFILES_DIRS = (
    '/absolute_path_to_project/mealmate/static',
)

to get this working. Of course, replace absolute_path_to_project with your actual path and, if necessary, add the drive letter.

Seth
  • 6,514
  • 5
  • 49
  • 58
8

I was also stuck in the 404 problem until I realized that Apache had blocked the requests to the static dir. I used python manage.py collectstatic to copy all the static files to the static dir under my project root, i.e. /var/my/site/static. With

Alias /static /var/my/site/static
<Directory /var/my/site/static>
        Require all granted
</Directory>

in /etc/httpd/conf/httpd.conf, it works properly now.

If none of the answers above works, you may consider checking your server config.

Darwin
  • 180
  • 1
  • 6
  • 1
    I had the Alias set to `Alias /static/ /var/my/site/static` as it is on https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/modwsgi/#serving-files, and changing the first call to `/static` fixed the problem for me. Thanks! – andrewec Nov 30 '17 at 23:34
7

If you are suffering from this error then first check that is the debug true or false and are you using 'STATIC_ROOT' and 'STATICFILES_DIRS' together

For my case I have used the followings in my settings.py:

import os #(You have to import os at first)
    
#(If the app is in production mode then False. By default True)

DEBUG = False 

#(If debug is false then add allowed hosts)

ALLOWED_HOSTS = ['*'] 

#(Built in)

STATIC_URL = '/static/' 

STATIC_ROOT = 'static' (You have to add it to the code)

STATICFILES_DIRS = [ os.path.join(BASE_DIR, '/static') ] (You have to add it to the code)
Osamoele
  • 371
  • 4
  • 15
Abindent
  • 81
  • 1
  • 6
6

In my case, all I had to do was re-run the server:

python manage.py runserver
Davor Josipovic
  • 5,296
  • 1
  • 39
  • 57
5

I'm assuming you're using Django1.3+ here.

First off, you need to define a few more settings:

STATICFILES_FINDERS = [
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]

STATICFILES_DIRS = [
    path.join(TOP_DIR, 'static'),
]

STATIC_ROOT = path.join(TOP_DIR, 'staticfiles')
STATIC_URL = '/static/'

This should help you find that directory.

Also, you should always access your static files using STATIC URL:

<link rel="stylesheet" href="{{ STATIC_URL }}css/bootstrap.min.css">
drewman
  • 1,565
  • 11
  • 15
  • 1
    Hi, I am using {{ STATIC_URL }}. It was a bit unclear, the html I showed was the rendered file to demonstrated that the tag was working. I am working locally so I thought that only a STATIC_URL setting was needed, so long as the /static directory was in place. – KindOfGuy Oct 10 '12 at 07:55
5

add below in setting.py

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]
yasin lachini
  • 5,188
  • 6
  • 33
  • 56
4

Make sure mealmate is in your INSTALLED_APPS

chrisortman
  • 1,514
  • 15
  • 22
4

in Django, you have one more option for your templates and it is linking statics like this.

this might solve your problem!

<script src="{% static 'myapp/bootstrap.min.js' %}"></script>
<link href="{% static 'myapp/bootstrap.css' %}" rel="stylesheet" type="text/css"/>

its better and easier to use

{% static 'filename' %}

for more information refer to , i refer you to https://docs.djangoproject.com/en/1.11/intro/tutorial06/

Ebrahim Karimi
  • 732
  • 8
  • 24
3

in my case my static files are in resources/static directory and I set some settings like blow in settings.py file :

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, './resources/static/'),
)

and using it in my template like this:

% load static %}
    <link rel="stylesheet" type="text/css" href="{% static '/plugins/bootstrap/css/bootstrap.css' %}">

this way worked for me.

ahmad-mohammadi
  • 157
  • 2
  • 5
2

change DEBUG variable to True in your settings.

the runserver method only looks for statics if debug is enabled, if not, it will look in the STATIC_ROOT url

1

Insert the following lines into settings.py in the main folder of your project:

STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join('static'))

Then, in the html file insert:

{% load static %}

Finally, within settings.py, add django.contrib.staticfiles into INSTALLED_APPS = [...]

Hayden Eastwood
  • 928
  • 2
  • 10
  • 20
1

On localhost, make sure to define DEBUG = True on settings.py

0

I think you missed to put the app INSTALLED_APPS in your settings.py file, you should add "mealmate"

INSTALLED_APPS = (
    'mealmate',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

After that the static and command files will be visible to django. I was having trouble with commands and this is the way I fixed it.

Omar Alvarado
  • 1,304
  • 2
  • 12
  • 16
0

on Cpanel this is good solution here

on terminal on cpanel install dj-static static3

pip install dj-static static3

then in wsgi.py replace this code py application

from dj_static import Cling

application = Cling(get_wsgi_application())
Youssri Abo Elseod
  • 671
  • 1
  • 9
  • 23
0

I faced same issue. Here how I solve of accessing static file in template.

My Django project(Recognition/) file directory look like this:

/media
   /1
     i1.jpg
     i2.jpg
     ....

/static
    /css
       /op.css
    /img
       /emoji.png

/Recognition
    ...
    /settings.py
    /urls.py
    ...

/uploader
    ...
    /urls.py
    /templates
         /uploader
             /create.html
    ...

My settings.py look like this:

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',
    'Recognition',
    'uploader',
]

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

My (Recognition/urls.py) look like this:

urlpatterns = [
    path('admin/', admin.site.urls),
    ...
]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Then I am accessing all static files and media files in template(create.html) like this: Here is sample code

<!DOCTYPE html>
<html>
<head>
   {% block extrahead %}
      <link rel="stylesheet" type="text/css" href="static/css/op.css">
   {% endblock %}
</head>

<style type="text/css">
.notfound .notfound-404 {
  ...
  background-image: url('static/img/emoji.png');
  ...
}
<style>

<body>
  <img src="{{ MEDIA_ROOT }}/media/i1.jpg" class="image_responsive" height="100px" width="100px">
</body>

OR

You can use this django command to see where django is seeing your static files. SOURCE

python manage.py collectstatic --help
Harshit Mahajan
  • 193
  • 2
  • 13
  • be careful when using `static` in your router file(Recognition/urls.py) because this only works when `DEBUG=True` which means only works on development environment. there are 2 warnings in source you provided – Wei Jing May 16 '23 at 22:31
0

for me, i do nothing but run manage.py runserver myip:port. Then i shut it down and restart uwsgi, the static files load successfully. I don't know why but it works for me...

0

I was able to solve this same problem by changing the js filename from camel case to snake case.

Ryan w
  • 528
  • 1
  • 7
  • 21
0

In django version 4.1.2 STATIC_ROOT is not working instead use STATICFILES_DIRS = [ BASE_DIR / "static" ]

0

as Django docs say; adding this code simple fixed my problem.

STATICFILES_DIRS = [
    BASE_DIR / "static",
]
0

I use the standard gitignore file found here for every project. It excludes various folder names. One of the libraries I was using just happen to name the folder after one in the gitignore file. Took me a while to figure that one out!

joshlsullivan
  • 1,375
  • 2
  • 14
  • 21
0

Seems like you're loading static files the wrong way in your template. The correct way to do it is,

For Django 1.6 or earlier

{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static "css/bootstrap.min.css" %}">

For Django 1.7 to 2.1

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static "css/bootstrap.min.css" %}">

For Django 2.2 or later

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css' %}">

EDIT:

If you specify the URL of your static files differently in settings, it'll work differently for different values of DEBUG. Here are two ways. (Tested on Djago 4.1)

1. This configuration will load static files when DEBUG=True

STATIC_URL = 'static/'

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

2. This configuration will load static files when DEBUG=False

STATIC_ROOT = BASE_DIR / 'static'

STATIC_URL = 'static/'

NOTE: Assuming your static files are present in the static folder in your project's root directory. Please hard refresh the browser window while testing. (For chrome hold ctrl while clicking refresh wheel)

  • 1
    I had to make DEBUG = True to make it work – anjanesh Mar 15 '23 at 05:22
  • Thank you @anjanesh for pointing out this issue. I've checked with different combinations of settings and found out that it's working differently for some settings. I'm updating the answer. – Harsh Dobariya Mar 15 '23 at 07:45
0

For nowadays solution please try Django package Whitenoise. It is easy to install and easy to use if you followed the instructions.

some simplified steps:

  1. Collect static - make sure static files existing before install

     python manage.py collectstatic
    
  2. Install the Whitenoise - this step depends how you managed the packages, update proper file(e.g. Pipfile or requirements.txt) and install. Below command just a example to install the package.

     pip install whitenoise
    
  3. Update the static root in settings.py

     STATIC_ROOT = BASE_DIR / "staticfiles"
    
  4. Add the following to your MIDDLEWARE in settings.py - from Whwitenoise docs, Whitenoise package should place after django.middleware.security.SecurityMiddleware

     `MIDDLEWARE = [
       'django.middleware.security.SecurityMiddleware',
       'whitenoise.middleware.WhiteNoiseMiddleware', #add it here exactly after security middleware
       ...
     ]
    
  5. now restart or rebuild the app to check whether it is working for you.

Please check Whitenoise docs if you running into issue about installing the Whitenoise(Whitenoise docs)

a message for using staticfiles_urlpatterns: this only works when DEBUG=True in settings.py which means you should NOT use it for production environment. see reference here

Wei Jing
  • 613
  • 5
  • 11
0

in my case that was the problem: root dir was project_name but app dir where static folder is was my_app, so django tried to find static files in project_name/static, when it was in project_name/my_app/static, so I updated STATICFILES_DIRS = ('my_app/static/',)

i also added after defining STATICFILES_DIRS in settings.py:

print('static paths are:')
for p in STATICFILES_DIRS:
    print(Path(p).resolve())

to find out which was the right place, so i could get this command output when run this command:

python manage.py findstatic --verbosity 3 css/main.css