How to use both static files and media together

Is it possible to use both static files and media in a project? because all tutorials use only one of them.

MEDIA_URL= 'media/'
MEDIA_ROOT = BASE_DIR / 'media'

STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / 'static/'
STATICFILES_DIRS = BASE_DIR / 'static/

I wrote this to setting. How am supposed to modify urls.py?

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('pages.urls')),
    path('users/',include('users.urls')),
    path('users/',include('django.contrib.auth.urls')),
    ] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

I wrote it this way but how should I add static urls?

You add the two lists generated by the static functions, so:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('pages.urls')),
    path('users/', include('users.urls')),
    path('users/', include('django.contrib.auth.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Note however that Django does not serve static or media files in production, and that you this will have to set up nginx, apache, or another webserver to do so.

To include the static URLs, you can use the static() function from Django's django.conf.urls.static module. This function takes two arguments: the URL prefix for the static files and the location of the static files on the server. You can use the STATIC_URL and STATIC_ROOT settings, which you have already defined in your settings.py file, to specify the URL prefix and the location of the static files.

Here's an example of how you can include the static URLs in your urlpatterns list:

from django.conf.urls.static import static

urlpatterns = [
    # ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

To include the media URLs, you can use the same static() function, but you will need to use the MEDIA_URL and MEDIA_ROOT settings, which you have also defined in your settings.py file. Here's an example of how you can include the media URLs in your urlpatterns list:

from django.conf.urls.static import static

urlpatterns = [
    # ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Keep in mind that the static() function should be added to the urlpatterns list at the end, after all the other URL patterns. This is because Django processes the URL patterns in the order they are listed, and you want the static and media URLs to be the last ones to be checked.

Back to Top