Django / Django File Uploads and Media Management

Managing Static and Media Files

This tutorial teaches you how to manage static and media files in a Django application. You'll learn how to organize and serve these files efficiently.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explains how to handle file uploads and manage media files in Django applications.

1. Introduction

In this tutorial, we will be exploring how to efficiently manage static and media files in a Django application.

Static files refer to your CSS and JavaScript files, while media files are often user-uploaded content, like images, audio files, etc. Django has a powerful system for managing these files so they can be served in a fast, optimized manner.

By the end of this tutorial, you should be able to:

  • Understand the difference between static and media files
  • Configure your Django application to handle static and media files
  • Serve these files in a production environment

This tutorial assumes you have a basic knowledge of Python and Django. If you are new to Django, you can first go through the Django documentation.

2. Step-by-Step Guide

Understanding Static and Media Files

In Django, static files include your CSS, JavaScript, and images that are not uploaded by the user. These are files that are part of your application and are the same for all users.

Media files, on the other hand, are typically generated by the users of your application. They could be profile pictures, uploaded documents, or any other user-generated content.

Setting up Static Files

To serve static files we need to:

  1. Set STATIC_URL in settings.py:
    STATIC_URL = '/static/'
    This tells Django where to look for static files.

  2. In your templates, you can use it like this:
    {% load static %} <img src="{% static "my_app/example.jpg" %}" alt="My image">
    Django will replace {% static "my_app/example.jpg" %} with /static/my_app/example.jpg.

  3. Run python manage.py collectstatic command. Django will copy all static files into STATIC_ROOT.

Setting up Media Files

To setup media files:

  1. Set MEDIA_URL and MEDIA_ROOT in settings.py:
    MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
    This tells Django where to look for and store media files.

  2. In your models, you can use FileField or ImageField:
    class MyModel(models.Model): upload = models.FileField(upload_to='uploads/')
    Django will store the uploaded file into MEDIA_ROOT/uploads.

3. Code Examples

Below is an example of how to setup static and media files in Django.

settings.py

# settings.py

import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

# Media Files (User uploaded files)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

models.py

# models.py

from django.db import models

class Profile(models.Model):
    profile_picture = models.ImageField(upload_to='profile_pictures/')

my_template.html

<!-- my_template.html -->

{% load static %}
<html>
    <head>
        <title>My Site</title>
        <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}">
    </head>
    <body>
        <img src="{{ profile.profile_picture.url }}" alt="Profile picture">
    </body>
</html>

4. Summary

In this tutorial, we learned:

  • The difference between static and media files in Django
  • How to configure Django to handle these files
  • How to serve these files in a production environment

If you want to learn more about managing static and media files, you can check the Django documentation on static files and file uploads.

5. Practice Exercises

To practice what you've learned, try the following exercises:

  1. Create a new Django project and configure it to serve static files. Add some CSS and JavaScript files and use them in a template.

  2. Add an ImageField to a model and create a form to upload images. Display the uploaded image in a template.

  3. Deploy your Django project on a server and configure it to serve static and media files in a production environment.

Remember that practice is the key to mastering any skill. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

AES Encryption/Decryption

Encrypt and decrypt text using AES encryption.

Use tool

Keyword Density Checker

Analyze keyword density for SEO optimization.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

File Size Checker

Check the size of uploaded files.

Use tool

Date Difference Calculator

Calculate days between two dates.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help