Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - putting static files inside app folder

Tags:

django

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

like image 250
André Luiz Avatar asked Dec 14 '22 05:12

André Luiz


1 Answers

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/)
like image 177
C14L Avatar answered Jan 11 '23 17:01

C14L