Reputation: 123
currently I am dealing with django static/staticfiles and I learnt a lot about static_url, static_root, staticfiles_dirs here at stackoverflow and in youtube tutorials. However I don't understand what "staticfiles_urlpatterns" does and when exactly I have to use it?
Thanks for an answer.
Upvotes: 8
Views: 4224
Reputation: 767
staticfiles_urlpatterns()
will serve files directly from
the locations specified in settings.STATICFILES_DIRS
.
static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
will serve files from settings.STATIC_ROOT
. This means you have to run collectstatic
first (and every time a static file changes), which will find files in STATICFILES_DIRS
and put them into STATIC_ROOT
.
Upvotes: 0
Reputation: 2357
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Your question is what does it have to do with urls.py
file?
Well i believe you must know about absolute_urls
and how they're constructed. well similarly prior to Django 2.0
we had to do this to tell that our static
request to go to settings.py
and look for static
variables which are then pointing to staticstorage
, eg , STATIC_ROOT & STATIC_URL
You don't need to add the following lines to the project's url.py in Django 2.0 because Django knows that it has to prefix the static file url path in the template with STATIC_URL:
urls.staticfiles_urlpatterns()
This will return the proper URL pattern for serving static files to your already defined pattern list. Used like this:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf here ...
urlpatterns += staticfiles_urlpatterns()
Upvotes: 5