how-to-upload-image-in-django

How to upload image in django

Hello World, Welcome to ProjectPlaza.com. 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/settings.py file on root.
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
  • import the following setting in the app/urls.py 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">
                        <tr>
                            <td>Choose Image</td>
                            <td><input type="file" name="profile_img" /></td>
                        </tr>
                        <tr>
                            <td colspan="2">
                                <input type="submit" value="Update" class="btn btn-dark btn-sm" />
                            </td>
                        </tr>
                    </table>
                </form>

Upload Image

  • Url setting for upload form
path('update-profile-image',views.update_profile_image,name='update-profile-image'),
  • Create method in views.py to upload the image
# Please Import the following setting at the top of file
from django.core.files.storage import FileSystemStorage
# Update Profile Image
def update_profile_image(request):
        if request.method=='POST':
            profile_img = request.FILES['profile_img']
            fs=FileSystemStorage(location='media/profile_imgs/')
            filename=fs.save(profile_img.name,profile_img)
            # uploaded_file_url=fs.url(filename)
            return redirect('/profile')
        else:
            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 *