[Fixed]-What Does Django static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Actually DO?

8👍

I think you are mixing up few things. Let me clarify.

static:

As per documentation, it provides URL pattern for serving static file. If you go to the implementation, then you will see:

return [
        re_path(r'^%s(?P<path>.*)$' % re.escape(prefix.lstrip('/')), view, kwargs=kwargs),
]

What it does is, it removes forward slash from left of the prefix(ie converts /static/ to static/), and then there is a view(which is serve) who does the pulling files.

serve:

This function does the serving files. It will serve files from a document root.

runserver:

runserver command runs the django development server. If you have django.contrib.staticfiles installed in INSTALLED_APPS, then it will automatically serve static files. If you don’t want to serve static, then use runserver --nostatic. collectstatic or STATIC_ROOT has no relation to this command.

collectstatic:

This command collects all static files from different STATIC_DIRS, and put them in folder which is defined by STATIC_ROOT. collectstatic is very useful in production deployment, when you are using a reverse proxy server like NGINX or Apache etc. NGINX/Apache/Varnish uses that folder (where collectstatic stored the static files) as root and serve static from it. It is not recommended to use runserver in production. You can use gunicorn/uwsgi to serve django. But gunicorn/uwsgi does not serve static files, hence using reverse proxy server to serve static files.

finally:

To answer your questions:

  1. No you don’t have to put that in your code, unless you are not adding django.contrib.staticfiles in your INSTALLED_APPS.

  2. No

  3. You don’t need to. STATIC_ROOT is used for different purpose

  4. It is not. But for serving MEDIA files, you can add the following pattern:

    if settings.DEBUG:
        urlpatterns += [
            re_path(r'^media/(?P<path>.*)$', serve, {
                'document_root': settings.MEDIA_ROOT,
            }),
        ]
    

In production, media files should be served by reverse proxy server as well.

👤ruddra

Leave a comment