Django: How to Manage Static files (e.g. images, CSS, JS)

Posted: October 02, 2024 | Updated: October 02, 2024

For Static Files

In Django, you can easily add static files (like images, JavaScript, and CSS) and media files (user-uploaded content). Here’s a guide on how to create and use static and media folders.

Step 1: Create a static folder (where manage.py is located)

myapp/
    static/
        myapp/
            css/
            js/
            images/

Step 2: Then Configure settings.py: Ensure your settings.py file includes the necessary configurations.

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    BASE_DIR / "static",  # Adjust BASE_DIR as necessary
]

Step 4: Add Images, CSS, and JS files in the static folder.

Step 5: Use static files in templates

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'myapp/css/styles.css' %}">
<script src="{% static 'myapp/js/scripts.js' %}"></script>
<img src="{% static 'myapp/images/logo.png' %}" alt="Logo">

Step 6: Collect Static Files (for production): When you deploy your application, run the following command to collect static files into a single directory:

python manage.py collectstatic

For Media files

Setting Up Media Files
Media files are typically user-uploaded content (like images or documents). Here’s how to set them up:

1. Create the Media Directory: Create a directory in your project root for media files. For example:

/myproject/
    media/

2. Configure settings.py: Add configurations for media files in your settings.py.

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

3. Handling File Uploads: In your models, use FileField or ImageField to handle uploads.

from django.db import models

class MyModel(models.Model):
    image = models.ImageField(upload_to='uploads/')

4. Serve Media Files in Development: During development, you need to serve media files. Update your urls.py:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # Your URL patterns here
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

5. Accessing Media Files: In your templates, you can access media files using:

<img src="{{ my_model_instance.image.url }}" alt="My Image">

Purpose

  • Static Files: Use the static directory for CSS, JavaScript, and images; configure STATIC_URL and STATICFILES_DIRS in settings.py.
  • Media Files: Use a dedicated media directory for user uploads; configure MEDIA_URL and MEDIA_ROOT, and serve them during development with urls.py.

© 2024 Webapptiv. All rights reserved.