
Let’s add a “profile picture” or “post image” to your models. Working with Django File Uploads means handling files involves three key parts: the Model, the Settings, and the Form.
Step 1: settings.py (The Setup)
Django needs to know where to save uploaded files. Add these two lines to the bottom of config/settings.py:
# settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'This tells Django to save all uploads in a folder named media at the root of your project.
Step 2: models.py (The Database)
We use a special field called ImageField. You’ll need to install Pillow first: pip install Pillow.
# pages/models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
text = models.TextField()
# Add this field! 'upload_to' creates subfolders
image = models.ImageField(upload_to='post_images/', blank=True, null=True)
def __str__(self):
return self.titleDon’t forget to run makemigrations and migrate!
Step 3: forms.py
The ModelForm handles this automatically.
# pages/forms.py
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'text', 'image'] # Add 'image'Step 4: The HTML Form (enctype)
This is the part everyone forgets! To upload files, your
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>Your form can now accept image uploads, which will be saved to your media/post_images/ folder.





