Django — Media Files
Media Settings
# settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
Model with Upload
class Post(models.Model):
title = models.CharField(max_length=200)
image = models.ImageField(upload_to='posts/%Y/%m/')
document = models.FileField(upload_to='documents/')
URL Configuration
# urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
# ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Template
{% if post.image %}
<img src="{{ post.image.url }}" alt="{{ post.title }}">
{% endif %}
Form with File Upload
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
File Handling in View
def post_create(request):
if request.method == 'POST':
form = PostForm(request.POST, request.FILES)
if form.is_valid():
post = form.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'blog/form.html', {'form': form})
Mini Practice
- Configure media settings
- Create a model with ImageField
- Handle file uploads in forms
- Display uploaded files
Up Next
Continue with Authentication — user login and registration.
Related Topics
Frequently Asked Questions about Media Files
What is Media Files in Django?
Media Files is a fundamental concept in Django. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Media Files?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Media Files.
Why is Media Files important in Django?
Media Files is essential for Django development. Understanding this concept will help you write better code and solve real-world problems more effectively.