Search code examples
django

When exactly do I need staticfiles_urlpatterns


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.


Solution

  • 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()