1

I'm trying to follow these instructions to enable static files in my Django project. I have

STATIC_URL = '/static/'

in my settings.py file. I have 'django.contrib.staticfiles', added to the INSTALLED_APPS = (...) part I created a folder mysite/static/mysite and put my files there. But after I run the server, I cannot access my files at http://127.0.0.1:8000/static/mysite/style.css. What I have done wrong?

user1460819
  • 2,052
  • 5
  • 26
  • 35

2 Answers2

1

In settings.py include this:

import os
settings_dir = os.path.dirname(__file__)
PROJECT_ROOT = os.path.abspath(os.path.dirname(settings_dir))

STATICFILES_DIRS = (
    os.path.join(PROJECT_ROOT, 'static/mysite/'),
)

And in your urls.py include these lines at the end:

from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()

Hope it helps.

Paulo Bu
  • 29,294
  • 6
  • 74
  • 73
0

I can suggest a couple things to check:

  • In my projects at least, the static folder is in the app directory, not the project directory. For example, mysite/myapp/static/myapp/img.jpg rather than mysite/static/mysite/img.jpg. Your project might not be looking in the right place.

  • Make sure that {% load staticfiles %} is in your html template before linking the files.

  • When you link a file in your html template, rather than direct urls like

<link rel="stylesheet" href="myapp/css/custom.css">

use

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

This was enough to get static files working in my projects, without having to modify urls.py or manually set PROJECT_ROOT or STATICFILES_DIRS.

Adam Stone
  • 1,986
  • 13
  • 16
  • I do not use constructions like `` , I simply try to access static files directly by .../static/style.css and this fails... – user1460819 May 06 '13 at 11:11
  • As the documentation you linked says, the template tag is preferable. It looks like both should work though, so the problem is likely that the files are not where the project can access them. If you put the static folder inside an app directory as I described above, it should find them automatically. But if you put them in the main project directory as you have described, you will have to add that to STATICFILES_DIRS in settings.py. Look just below point number 4 in the documentation you linked and it explains how to do this. – Adam Stone May 06 '13 at 18:19