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 namedimage_uploadand an app calledimage_app, where users can upload hotel images.
1. Configure settings.py
Add the following settings to handle media files:
PythonMEDIA_ROOT=os.path.join(BASE_DIR,'media')MEDIA_URL='/media/'
- MEDIA_ROOTdefines the server-side file path for storing uploaded files.
- MEDIA_URLprovides the browser-accessible URL to access those files.
2. Configure urls.py for Serving Media
Add this code to your project’surls.py:
Pythonfromdjango.confimportsettingsfromdjango.conf.urls.staticimportstaticurlpatterns=[# your existing URL patterns]ifsettings.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 modelHotelinmodels.py underimage_app:
Pythonfromdjango.dbimportmodelsclassHotel(models.Model):name=models.CharField(max_length=50)hotel_Main_Img=models.ImageField(upload_to='images/')def__str__(self):returnself.name
- ImageFieldis used for image uploads.
- upload_to='images/' tells Django to store uploaded images inside the media/images/folder.
4. Create a Model Form
Create aforms.py file in your app and define the form:
Pythonfromdjangoimportformsfrom.modelsimportHotelclassHotelForm(forms.ModelForm):classMeta:model=Hotelfields=['name','hotel_Main_Img']
Django’sModelFormautomatically generates form fields based on the model.
5. Create an HTML Template
Create a template namedhotel_image_form.html inside the templates directory:
html<!DOCTYPE html><html><head><title>Upload Hotel Image</title></head><body><formmethod="POST"enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }}<buttontype="submit">Upload</button></form></body></html>
Explanation:
- enctype="multipart/form-data"is required for file uploads.
- {% csrf_token %} is for security againstCSRFattacks.
- {{ form.as_p }} renders each form field wrapped in <p> tags.
6. Create Views
In views.py, write the view to handle form submission:
Pythonfromdjango.shortcutsimportrender,redirectfromdjango.httpimportHttpResponsefrom.formsimportHotelFormfrom.modelsimportHoteldefhotel_image_view(request):ifrequest.method=='POST':form=HotelForm(request.POST,request.FILES)ifform.is_valid():form.save()returnredirect('success')else:form=HotelForm()returnrender(request,'hotel_image_form.html',{'form':form})defsuccess(request):returnHttpResponse('Successfully uploaded!')
7. Add URL Patterns
Update urls.py to include paths for image upload and success page:
Pythonfromdjango.urlsimportpathfrom.viewsimporthotel_image_view,successfromdjango.confimportsettingsfromdjango.conf.urls.staticimportstaticurlpatterns=[path('image_upload/',hotel_image_view,name='image_upload'),path('success/',success,name='success'),]ifsettings.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:
Pythondefdisplay_hotel_images(request):hotels=Hotel.objects.all()returnrender(request,'display_hotel_images.html',{'hotel_images':hotels})
Template: display_hotel_images.html
html<!DOCTYPE html><html><head><title>Hotel Images</title><linkrel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"></head><body><divclass="container"><divclass="row"> {% for hotel in hotel_images %}<divclass="col-md-4"><h4>{{ hotel.name }}</h4><imgsrc="{{ 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