Django Framework Static and Media Files


Django Framework Static and Media Files

What are Static and Media Files in Django?

The Django Framework allows us to efficiently manage static and media files while developing modern web applications. Static files are unchanging files such as CSS, JavaScript, and images, while media files represent files uploaded by users (for example, profile photos, documents). With proper configuration, it is guaranteed that these files are served correctly in Django projects both during the development process and in production.

Configuring Static and Media Files

settings.py Settings

To define the static and media files of your Django project, you need to make the following settings in the settings.py file:


# settings.py
i mport os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

URL Redirects

To serve static and media files in a development environment, edit your main URL file as follows:


# urls.py
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    # ... other URLs ...
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Using Static in Template

To use static and media files in a Django template, you can add static and media paths as follows:

{% load static %}
<link rel="stylesheet" href="{% static 'css/styles.css' %}">
<img src="{{ user.profile.image.url }}" alt="Profile Photo">

Conclusion: File Management in Django

In our article titled Django Framework Static and Media Files, we saw how static and user-specific files are configured and properly managed in projects. With the correct adjustments, the scalability and security of your project increase significantly. In particular, extra care must be taken regarding static and media management in the production environment. Django's robust infrastructure makes all these processes easy and flexible to implement.