Support
Please support this website. Visit the Amazon using this affiliate link. There won't be any difference in your purchage, we will get some commission for every purchase you make.
Advertise with us
upload django   0   18706
How to upload an Image file in Django


If you are looking for a way to upload and use the image on your Django website, then this article is for you. Follow these simple steps to upload an image or any file in your Django application.



Create an HTML form with a file upload field

<div class="row">
<div class="col-md-8 col-sm-8">
<form action="{% url 'appname:upload_image' %}" method="post" enctype="multipart/form-data"
class="form-horizontal">
{% csrf_token %}
<input type="file" name="image" class="form-control" required>
<input type="submit" value="Upload" class="btn btn-primary btn-sm">
</form>
</div>
</div>


Take a not of attribute enctype in the form tag. This is mandatory to upload files from HTML forms.


file upload django


Create a path entry in urlpatters

path(r'image/upload/', views.upload_image, name='upload_image'),



Create a model to store the image-related information

import os

from django.db import models


def upload_path(instance, filename):
# change the filename here is required
return os.path.join("uploads", filename)


class ImageModel(models.Model):
image = models.ImageField(upload_to=upload_path, null=False, blank=True)
created_date = models.DateTimeField(null=False, blank=True, auto_now_add=True)


upload_to parameter specifies where the uploaded image will be stored. It can take the value of a string defining the path or it can be callable. In the example above, we have used a callable. In the callable method, you can decide the upload path or change the filename if required. The first parameter in callable is the instance of the model where Image or FileField is defined.

The image will be uploaded to the "uploads" directory inside MEDIA_ROOT. 



Define the MEDIA_ROOT in settings.py file

MEDIA_ROOT = os.path.join(BASE_DIR, "media/")

Create a directory "media" in the project working directory. The value of MEDIA_ROOT could be anything you want. You can store it in another directory named 'abc'. In that case, MEDIA_ROOT will be defined as below.

MEDIA_ROOT = os.path.join(BASE_DIR, "abc/")



Create a view to accept the post request on HTML form submit

from blog.models import ImageModel

def upload_image(request):
data = dict()
if "GET" == request.method:
return render(request, 'blog/upload_image.html', data)

# process POST request
files = request.FILES # multivalued dict
image = files.get("image")
instance = ImageModel()
instance.image = image
instance.save()
return render(request, 'blog/upload_image.html', data)


In the code above, we are getting FILES from request and then from files dictionary getting the image. The type of image is InMemoryUploadFile.


Once the code is executed in view, the image will be uploaded to project-working-directory/media/uploads/image-file-name.extension path.



Using the uploaded image in your template

The path where your image is stored is /media/uploads/filename.jpeg. To use the image in the HTML template, we need to have a relative path and to use in emails we need to have the full path. For this, we need to define the MEDIA_URL in settings.py file.

MEDIA_URL = '/media/'

You can change the value of MEDIA_URL as per your requirement.

Now let's say your filename was cat.jpeg then your relative URL will be /media/uploads/cat.jpeg and your absolute URL will be http://example.com/media/uploads/cat.jpeg

The media string in the URL is the value of MEDIA_URL. For example, if you set the value of MEDIA_URL to 'xyz' then the path will be http://example.com/xyz/uploads/cat.jpeg


Read also: How to compress the uploaded image before storing it in Django.


Host your Django Application for free on PythonAnyWhere. If you want full control of your application and server, you should consider DigitalOcean. Create an account with this link and get $100 credits.

upload django   0   18706
0 comments on 'How To Upload An Image File In Django'
Login to comment


Related Articles:
How to validate an uploaded image in Python Django
Validating image before storing it in database or on file storage. Checking the size of uploaded image in python django. Checking the extension of uploaded image in python django. Checking the content size of uploaded image. Checking the mime-type of uploaded Image. Validating a malicious image before saving it. Using python-magic package...
Uploading a file to FTP server using Python
Uploading files to FTP server using Python, Python script to connect to ftp server, Python code to login to FTP server and upload file, How to connect to FTP server using python code, ftplib in python, Get server file listing using ftplib in python...
How to upload and process the Excel file in Django
How to upload and process the content of excel file in django without storing the file on server. Process Excel file content in Django. Uploading and reading Excel file content in Django 2.0 without storing it on server....
Creating a bar chart in Django Application
Minimal example of how to create a bar chart or pie chart in Django application using Charts.js. Drawing Analytics charts in Django application. Using charts and graphs to make your Django application visually appealing. Creating Dashboards using Charts.js in Django to convey the information more visually....
DigitalOcean Referral Badge

© 2022-2023 Python Circle   Contact   Sponsor   Archive   Sitemap