1000 Python Questions
Get 1 Python question daily. Join this telegram channel https://t.me/python1000questions
Advertise with us
upload django   0   5690
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   5690

Related Articles:
How to reset Django superuser password
This article explains 3 methods to reset the user password in Django, What command should be used to reset the superuser password from the terminal in Django application, Changing the user password in Django...
Encryption-Decryption in Python Django
How to encrypt and decrypt the content in Django, Encrypting the critical information in Django App, Encrypting username, email and password in Django, Django security...
Getting query params from request in Django
In this article, we will see how to access the query parameters from a request in the Django view, Accessing GET attribute of request, get() vs getlist() method of request in Django, query parameters Django,...
Hello Word in Django 2: How to start with Django 2
In this article, we will see how to start working with Django 2.2, Step by step guide to install Django inside a virtual environment and starting the application on localhost, Django 2.2 installation, first Django project, hello world in Django 2.2, First Django application...

0 thoughts on 'How To Upload An Image File In Django'
Leave a comment:


*All Fields are mandatory. **Email Id will not be published publicly.

SUBSCRIBE
Please subscribe to get the latest articles in your mailbox.

© 2017-2020 Python Circle   Contact   Sponsor   Archive   Sitemap