Uploading images in Django - Python
Last Updated :
11 Jul, 2025
Prerequisite - Introduction to Django
Uploading and managing image files is a common feature in many web applications, such as user profile pictures, product images, or photo galleries. In Django, you can handle image uploads easily using the ImageField in models.
In this article, we’ll walk through a simple project named image_upload and an app called image_app, where users can upload hotel images.
Add the following settings to handle media files:
Python
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
- MEDIA_ROOT defines the server-side file path for storing uploaded files.
- MEDIA_URL provides the browser-accessible URL to access those files.
Add this code to your project’s urls.py:
Python
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# your existing URL patterns
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This ensures that media files are served during development.
3. Create the Model
Create a model Hotel in models.py under image_app:
Python
from django.db import models
class Hotel(models.Model):
name = models.CharField(max_length=50)
hotel_Main_Img = models.ImageField(upload_to='images/')
def __str__(self):
return self.name
- ImageField is used for image uploads.
- upload_to='images/' tells Django to store uploaded images inside the media/images/folder.
Create a forms.py file in your app and define the form:
Python
from django import forms
from .models import Hotel
class HotelForm(forms.ModelForm):
class Meta:
model = Hotel
fields = ['name', 'hotel_Main_Img']
Django’s ModelForm automatically generates form fields based on the model.
5. Create an HTML Template
Create a template named hotel_image_form.html inside the templates directory:
html
<!DOCTYPE html>
<html>
<head>
<title>Upload Hotel Image</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
</body>
</html>
Explanation:
- enctype="multipart/form-data" is required for file uploads.
- {% csrf_token %} is for security against CSRF attacks.
- {{ form.as_p }} renders each form field wrapped in <p> tags.
6. Create Views
In views.py, write the view to handle form submission:
Python
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .forms import HotelForm
from .models import Hotel
def hotel_image_view(request):
if request.method == 'POST':
form = HotelForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('success')
else:
form = HotelForm()
return render(request, 'hotel_image_form.html', {'form': form})
def success(request):
return HttpResponse('Successfully uploaded!')
7. Add URL Patterns
Update urls.py to include paths for image upload and success page:
Python
from django.urls import path
from .views import hotel_image_view, success
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('image_upload/', hotel_image_view, name='image_upload'),
path('success/', success, name='success'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
8. Run Migrations and Test
Run the following commands:
python manage.py makemigrations
python manage.py migrate
python manage.py runserver
Visit the development server URL- http://localhost:8000/image_upload/ in your browser. Upload an image, and you’ll be redirected to the success page.
Output:
Snapshot of /image_upload endpointAfter uploading the image it will show success.
Snapshot of successful uploadNow in the project directory media directory will be created, an images directory will be created and the image will be stored under it. Here is the final result.
Snapshot of media directory being createdDisplay Uploaded Images
We can write a view for accessing the uploaded images, for simplicity let's take example with one image and it is also applicable for many images:
Python
def display_hotel_images(request):
hotels = Hotel.objects.all()
return render(request, 'display_hotel_images.html', {'hotel_images': hotels})
Template: display_hotel_images.html
html
<!DOCTYPE html>
<html>
<head>
<title>Hotel Images</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
{% for hotel in hotel_images %}
<div class="col-md-4">
<h4>{{ hotel.name }}</h4>
<img src="{{ hotel.hotel_Main_Img.url }}" class="img-responsive" style="width: 100%;">
</div>
{% endfor %}
</div>
</div>
</body>
</html>
Update urls.py:
path('hotel_images/', display_hotel_images, name='hotel_images'),
Below is the result when we try to access the uploaded images by visiting URL- http://127.0.0.1:8000/hotel_images/
Snapshot of /hotel_images endpoint
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice