Uploading images in Django - Python
Last Updated :
15 May, 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
Similar Reads
Django Models
A Django model is the built-in feature that Django uses to create tables, their fields, and various constraints. In short, Django Models is the SQL Database one uses with Django. SQL (Structured Query Language) is complex and involves a lot of different queries for creating, deleting, updating, or a
10 min read
Django ORM - Inserting, Updating & Deleting Data
Django's Object-Relational Mapping (ORM) is one of the key features that simplifies interaction with the database. It allows developers to define their database schema in Python classes and manage data without writing raw SQL queries. The Django ORM bridges the gap between Python objects and databas
4 min read
Django Basic App Model - Makemigrations and Migrate
Django's Object-Relational Mapping (ORM) simplifies database interactions by mapping Python objects to database tables. One of the key features of Django's ORM is migrations, which allow you to manage changes to the database schema.What are Migrations in Django?Migrations are files that store instru
4 min read
Add the slug field inside Django Model
The slug field within Django models is a pivotal step for improving the structure and readability of URLs in web applications. This addition allows developers to automatically generate URL-friendly slugs based on titles, enhancing user experience and search engine optimization (SEO). By implementing
4 min read
Intermediate fields in Django - Python
Prerequisite: Django models, Relational fields in DjangoIn Django, a many-to-many relationship is used when instances of one model can be associated with multiple instances of another model and vice versa. For example, in a shop management system:A Customer can purchase multiple Items.An Item can be
2 min read
Uploading images in Django - Python
Prerequisite - Introduction to DjangoUploading 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
3 min read
Change Object Display Name using __str__ function - Django Models | Python
How to Change Display Name of an Object in Django admin interface? Whenever an instance of model is created in Django, it displays the object as ModelName Object(1). This article will explore how to make changes to your Django model using def __str__(self) to change the display name in the model. Ob
2 min read
Custom Field Validations in Django Models
In Django, field validation is the process of ensuring that the data entered into a field meets certain criteria. Custom field validation allows us to enforce rules such as checking for specific formats, length restrictions or even more complex conditions, like validating an email to belong to a spe
3 min read
Meta Class in Models - Django
Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. Itâs free and open source. D
3 min read
How to use Django Field Choices ?
Djangoâs choices option lets you limit a model field to a fixed set of values. It helps keep your data clean and consistent, and automatically shows a dropdown menu in forms and the admin instead of a text box.Choices are defined as pairs: the first value is saved to the database, and the second is
2 min read