Django upload image to database
In this article, you will learn the simple process of uploading an image using the Django and adding it to the Django model with the help of the ImageField model.
In most of these applications, we need the image upload functionality. Django comes with pre-defined packages and methods that make this task easier. It enables fast development of any type of web application. Like other programming languages, it can easily connect with a database. Here, we have explained the image upload process in detail.
These are the step-by-step instructions to upload an image using Django
Suppose we have the following MySQL table 'imageupload'-
CREATE TABLE IF NOT EXISTS `imageupload` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` char(200) NOT NULL,
`img` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
In this article, we have created a new Django project 'uploadimage' and a new app 'imagefield' to develop an image upload process.
(env) c:\python37\Scripts\projects>django-admin startproject uploadimage
(env) c:\python37\Scripts\projects>cd uploadimage
(env) c:\python37\Scripts\projects\generatecsv>django-admin startapp imagefield
models.py
The model helps to map the fields to the database. It represents a database table. In this project, we are taking the image title and its image from the user. So, the code of 'models.py' is-
from django.db import models
# Create your models here.
class ImagefieldModel(models.Model):
title = models.CharField(max_length = 200)
img = models.ImageField(upload_to = "images/")
class Meta:
db_table = "imageupload"
By default, the image is uploaded to the media directory. So, we no need to specify them.
forms.py
The ModelForm is required to collect the form data. So, we have created a ModelForm, 'forms.py' under the 'imagefield' app, whose fields are taken from the database table.
from django import forms
class ImagefieldForm(forms.Form):
name = forms.CharField()
image_field = forms.ImageField()
Create HTML Template file
Next, we have created a template directory under 'imagefield' app, where we have created an HTML template file 'fileupload.html' that calls the browser for uploading the image.
<html>
<head>
<title>Django File Upload</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
</body>
</html>
views.py
We have placed the following code in 'views.py'. It takes the form request and returns the response. The 'obj.save()' method is used to save the form data to the database. On a successful image upload, it returns a success message.
from django.shortcuts import render
from django.http import HttpResponse
from .forms import ImagefieldForm
from .models import ImagefieldModel
# Create your views here.
def home_view(request):
context = {}
if request.method == "POST":
form = ImagefieldForm(request.POST, request.FILES)
if form.is_valid():
name = form.cleaned_data.get("name")
img = form.cleaned_data.get("image_field")
obj = ImagefieldModel.objects.create(
title = name,
img = img
)
obj.save()
print(obj)
return redirect('success')
else:
form = ImagefieldForm()
context['form'] = form
return render( request, "fileupload.html", context)
def success(request):
return HttpResponse('successfully uploaded')
urls.py
At last, we have added path to route page to the particular link.
from django.contrib import admin
from django.urls import path
from imagefield import views
urlpatterns = [
path('uploadimage', views.home_view),
]
Here, we are migrating the project.
(env) c:\python37\Scripts\projects\uploadimage>python manage.py migrate
After migration, run the project using the following command-
(env) c:\python37\Scripts\projects\uploadimage>python manage.py runserver
If everything is correct, then it returns something like this-
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Related Articles
Python | Uploading images in DjangoDjango pass variable from view to HTML template
How to read and write a file using Django
Django serialize queryset into JSON and display in template
Django Export Model Data to CSV
Django Custom User Model SignUp, Login and Logout
How to display image from database in Django
Django Pagination with Ajax and jQuery
Django download file
Django Simple File Upload
Django ajax GET and POST request
Django bootstrap 4 form template
Django upload image to database
Windows command to create and run first Django app
Django Send Mail on Contact form submission
How to insert data in MySQL database from an HTML form using Django
Convert MySQL query result to JSON in Python
Display data from MySQL in HTML table using Python
Insert XML Data to MySQL Table using Python
CRUD operations in Python using MYSQL Connector