How to upload image in django

Hello World, Welcome to Today we will discuss how to upload image in Django. We will create a simple form to upload a single image. We will upload an image with Django core FileSystemStorage package.  I have divided this tutorial into the following parts:

I have assumed that you have basic knowledge of Django. If not then please see this tutorial.

  • Path setting for upload folder
  • Create upload form
  • Upload Image

Path setting for upload folder

In this step, we will set the folder path with the URL to upload image and shows.

  • Add the following code to project/ file on root.
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
  • import the following setting in the app/ file
from django.conf import settings
from django.conf.urls.static import static
  • Concatenate the following code with urlpatterns variable.
urlpatterns+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


Create Upload Form

In this step, we will create a form to upload an image.

  • Create templates/upload.html and add the following code.
<form method="post" action="/update-profile-image" enctype="multipart/form-data">
                    {% csrf_token %}
                    <table class="table table-bordered">
                            <td>Choose Image</td>
                            <td><input type="file" name="profile_img" /></td>
                            <td colspan="2">
                                <input type="submit" value="Update" class="btn btn-dark btn-sm" />

Upload Image

  • Url setting for upload form
  • Create method in to upload the image
# Please Import the following setting at the top of file
from import FileSystemStorage
# Update Profile Image
def update_profile_image(request):
        if request.method=='POST':
            profile_img = request.FILES['profile_img']
            # uploaded_file_url=fs.url(filename)
            return redirect('/profile')
            return HttpResponse('Invalid response!!')

I hope you have enjoyed this tutorial. Please add your feedback in the comment section.

Leave a Reply

Your email address will not be published. Required fields are marked *