Uploading Media
Handle user-uploaded files — configure Django media settings to accept and serve uploaded images like article thumbnails.
Uploading Media
Media files are user-uploaded files (images, documents). They are different from static files, which are part of your project code. Django needs separate configuration for media.
Media Settings
# djangoblog/settings.py
import os
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Serving Media in Development
# djangoblog/urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('articles/', include('articles.urls')),
]
# Only in development:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
The ImageField
# articles/models.py
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField()
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
thumb = models.ImageField(default='default.png', blank=True)
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
Install Pillow for image handling: pip install Pillow
Displaying Uploaded Images
<!-- In a template -->
<img src="{{ article.thumb.url }}" alt="{{ article.title }}">
article.thumb.url returns the full URL path to the uploaded image.
Upload via Admin
With the ImageField configured, the Django admin automatically shows a file upload widget. Upload images through the admin panel to test.
Key Takeaways
- Configure
MEDIA_URLandMEDIA_ROOTin settings for user uploads - Add the static URL pattern for serving media in development
ImageFieldrequires Pillow:pip install Pillow- Access the file URL in templates with
{{ field.url }}