In Part 5, we built a user dashboard with content management. Now, let’s enable media uploads so users can upload images and files with their posts or profiles. We’ll configure media settings, add upload fields, and display uploaded files in templates.
What You’ll Learn
- Configure
MEDIA_ROOT
andMEDIA_URL
- Create upload fields for images/files
- Update views and templates to handle file uploads
- Serve uploaded files in development
Step 1: Configure Media Settings
In settings.py
, add:
import os
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
In urls.py
(project-level), add the following at the bottom:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Step 2: Add an Image Field to Your Post Model
In models.py
:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
image = models.ImageField(upload_to='post_images/', blank=True, null=True)
def __str__(self):
return self.title
Run migrations:
python manage.py makemigrations
python manage.py migrate
Step 3: Update the Post Form
In forms.py
:
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'content', 'image']
Step 4: Update the Create & Edit Views
Make sure your views accept file uploads:
def create_post(request):
if request.method == 'POST':
form = PostForm(request.POST, request.FILES)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.save()
return redirect('dashboard')
else:
form = PostForm()
return render(request, 'myapp/create_post.html', {'form': form})
def edit_post(request, pk):
post = get_object_or_404(Post, pk=pk, author=request.user)
form = PostForm(request.POST or None, request.FILES or None, instance=post)
if form.is_valid():
form.save()
return redirect('dashboard')
return render(request, 'myapp/edit_post.html', {'form': form})
Step 5: Update Your Templates
create_post.html and edit_post.html should use enctype="multipart/form-data"
:
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
Step 6: Display the Uploaded Image
In your dashboard template or post list:
{% if post.image %}
<img src="{{ post.image.url }}" alt="Post Image" width="200" />
{% endif %}
Optional: Upload Files to Profile
To allow users to upload profile pictures or documents, add fields to the Profile
model (see Part 4):
profile_pic = models.ImageField(upload_to='profiles/', blank=True)
resume = models.FileField(upload_to='resumes/', blank=True)
Step 7: Install Pillow
For image handling, make sure Pillow is installed:
pip install Pillow
Conclusion
You’ve successfully added image and file upload functionality to your Django project. Now your users can upload profile pictures, images with posts, or other media. This is a key feature for blogs, portfolios, and content-based platforms.
Coming Next in Part 7: Build a contact form with email functionality using Django’s built-in email system!