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.
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.