Forums

css and js are not loading

when I change debug=False and add allowed host into the setting

DEBUG = FALSE
TEMPLATE_DEBUG = FALSE
ALLOWED_HOSTS = [ "myusername.pythonanywhere.com"]

the html pages are only plain text and image. Once I change DEBUG = True, it works perfectly.

why is that and how to fix it

[ edited by admin: formatting ]

I just checked out your website, and it looks like everything's OK now, so I guess you've worked out the solution :-) But here's the answer just in case someone else comes to this page with the same problem.

CSS, JavaScript, and so on disappear when you switch debug mode off if you haven't set up static file mappings.

When it's running in debug mode, Django serves up your static files -- your CSS, JavaScript, and images -- itself. This is really inefficient and slow, and no good for a production site, but is OK for testing.

When it's not in debug mode, it expects you to have configured a faster web server to serve up the static files. On PythonAnywhere, the way you do that is by adding mappings to the "Static files" section of your web app's section of the "Web" tab.

For a normal Django app, to make it work just like it did when it was in debug mode all you need to do is add one or two mappings:

  • One with the "URL" set to the value that was in the STATIC_URL setting from your settings.py, and the directory set to the full path to the directory you had specified in STATIC_ROOT. This one will handle all of your own static files. Do remember that you have to put the path in there explicitly -- you can't use os,path.join, BASE_DIR, or any of the other Python-y things you might use in settings.py. If you're using Django's collectstaric command, this is the only one you need.
  • Optionally, if you're not using collectstatic, one for the Django admin. This will vary based on which version of Django you're using, which version of Python, and whether or not you're using a virtualenv. The "URL" will always be /static/admin/, and to find the "Directory", the best thing to do is to start a Bash console, go into the virtualenv if you're using one, then run python3.4 -c "import django; print (django.__file__)" (change the 3.4 to the appropriate Python version, or remove it entirely if you're using a virtualenv). This will print out something like /usr/local/lib/python3.4/dist-packages/django/__init__.py. Copy it, paste it into the "Directory" field, then remove the __init__.py from the end and replace it with contrib/admin/static/admin/.