4

I've started an django app in an existing project and I'm trying to follow the project's pattern to organize stuff. In other apps I see that the static files are in the app itself, eg: File path: appname/static/js/file.js Javascript, inside the template: <script src="{% static 'js/file.js' %}"></script>

This works in other apps. I'm trying to do the same but the rendered file url gives me a 404 error.

What should I be checking to make it work? I've looked in the settings file, but there is nothing special there nor in the urls.

Thanks for any help

André Luiz
  • 5,730
  • 8
  • 49
  • 91
  • What does the error message on the page display, given that you have set `DEBUG=True` in the settings file? – Martin Hallén Jun 17 '16 at 17:07
  • 'js/file.js' could not be found – André Luiz Jun 17 '16 at 17:11
  • Well, this should't return a 404 error, are you sure there are not any other error messages. Could you give all the details given when you get a 404? – Martin Hallén Jun 17 '16 at 17:14
  • Have you added your app to installed apps in the settings? – Arun Ghosh Jun 17 '16 at 17:16
  • @mart0903 Request Method: GET Request URL: http://localhost:8001/static/file.js Raised by: django.contrib.staticfiles.views.serve 'js/file.js' could not be found You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. – André Luiz Jun 17 '16 at 17:20
  • Have you added your app to the `INSTALLED_APPS` in `settings.py`? – Martin Hallén Jun 17 '16 at 17:22
  • Also, check this question. I suspect this might be the same problem. http://stackoverflow.com/questions/6014663/django-static-file-not-found – Martin Hallén Jun 17 '16 at 17:23

1 Answers1

13

The path appname/static/ is the default that Django will look for in every installed app, no settings needed. Make sure your new app is actually listed in settings.INSTALLED_APPS.

Since you are on the development server, maybe you are missing the static file URLs. Make sure this is at the end of urls.py:

if settings.DEBUG:
    from django.contrib.staticfiles.urls import staticfiles_urlpatterns
    urlpatterns += staticfiles_urlpatterns()

That adds URL path /static/ for all files in any appname/static/.

Also, if you have more directories (not appname/static/) that you want to map to a URL path when using the development server, you could add then with static() like this

if settings.DEBUG:
    from django.conf.urls.static import static
    urlpatterns += static('/pics/', document_root=/var/www/pictures/)
C14L
  • 11,487
  • 4
  • 34
  • 50