How to View Uploaded Files in Django

In this Python Django tutorial, I will show you how to view uploaded files in Django, where you will upload the file on the Django server and view that file in your browser.

Basically, you will upload the image through the Django form and after uploading the image, you will see the uploaded image on your front-end side. This is the general concept that you can use it view any file on your browser.

How to View Uploaded Files in Django Project Set-Up

First, create a virtual environment named ‘env’, so open the terminal and run the following command:

python -m venv env

Activate the environment using the below code.

env\Scripts\activate

Install the latest version of Django.

pip install django

Create a project named ‘view_proj’ by typing the below command.

django-admin startproject view_proj

Change the directory to the Django project ‘view_proj’ using the below command.

cd view_proj

Create an app named ‘view_app’ using the below command.

python manage.py startapp view_app
How to View Uploaded Files in Django Project Set-Up

Now, you must install an application. for that add the Django app ‘view_app’ in the settings.py file of your Django project ‘view_proj’.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'view_app'
]
Installing App How to View Uploaded Files in Django Project Set-Up

Now add the URL path for the media folder where uploaded files will be saved so add the following lines to the end of the settings.py file of your Django project.

import os
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
How to View Uploaded Files in Django Project Set-Up Media URL

In the Django project ‘view_proj’ folder, make a new folder called ‘media’ that you have specified in the setting.py file.

Media Folder How to View Uploaded Files in Django Project Set-Up

Then open the urls.py file of your Django project ‘view_proj’ and add the following lines of code.

from django.contrib import admin
from django.urls import path, include
from django.conf import settings  
from django.conf.urls.static import static  

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('view_app.urls'))
]

if settings.DEBUG:  
        urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
How to View Uploaded Files in Django Project Set-Up URL

In the above code

  • Here, we serve files uploaded by users from MEDIA_ROOT during development by adding static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT).
  • Here, MEDIA_URL is kept as ‘media’ and document_root is the location of the uploaded file inside the media folder.
  • But, it only works when DEBUG is set to True and the URL specified in the settings is local as you can see in lines 11 and 12.
READ:  Attributeerror: Module 'tensorflow' has no attribute 'sparse_tensor_to_dense'

Now create a new file called urls.py in your Django app ‘view_app’ and in that newly created file add the following line code.

from django.urls import path
from . import views
urlpatterns = [
path('upload', views.Upload, name='upload'),
]
App URLs How to View Uploaded Files in Django Project Set-Up

How to View Uploaded Files in Django Creating Model and Forms

Create a model named UploadImage that represents the table in the database. Add the following lines of code in the models.py file of your Django app ‘.

from django.db import models

class UploadImage(models.Model):
    title = models.CharField(max_length=200)
    image = models.ImageField(upload_to='images/')
How to View Uploaded Files in Django Creating Model

Now create a form where the user will upload the file, so create a new file called forms.py in your Django app ‘view_app’ and add the following lines of code.

from django import forms  
from .models import UploadImage

class UploadImageForm(forms.ModelForm):
    class Meta:
        model = UploadImage
        fields = ['title', 'image']
How to View Uploaded Files in Django Creating Forms

View Uploaded Files in Django Creating View and Template

Create a view named Upload in the views.py file of your Django app ‘view_app’ by adding the following lines of code.

from django.shortcuts import render
from .forms import UploadImageForm

def Upload(request):
    if request.method == 'POST':
        form = UploadImageForm(request.POST,request.FILES)
        if form.is_valid():
            form.save()
            img_object = form.instance
            return render(request, 'ImageUpload.html', {'form': form, 'img_obj': img_object})
    else:
        form = UploadImageForm()
    context = {
            'form':form,
        }
    return render(request, 'ImageUpload.html', context)
View Uploaded Files in Django Creating View

In the above code from lines 1 to 2 import the function render from django.shortcuts and a form UploadImageForm from the forms.py file.

  • Then from lines 4 to 16 define the view named ‘Upload’, and this function takes an argument request in the form of an object. At line 5 it checks if the incoming request is POST method or not.
  • If the incoming request is the POST, then it creates a form instance using the UploadImageForm by passing the (request.POST which represents the submitted form data) and the files (request.FILES which represent the uploaded files) that come with a request at line 6.
READ:  How to convert Python file to exe using Pyinstaller

After this line 7 checks if the form is valid or not by calling the method save() on the form instance. if the form is valid, it does the following things:

  • First, it saves the uploaded data such as images to the specified location ( such as the media folder in your Django project).
  • After saving the forms, the form attribute instance contains the actual model instance that is saved using the form.save(), so the code img_object = form.instance gets that instance which is the uploaded image in this case.
  • At line 10 rendering the template ‘imageupload.html’ with a context that contains the form and the uploaded image object.

Then at line 12 in the else part, if the incoming request is not POST, then an empty form is initialized using the form = UploadImageForm(). At line 16, render the template ‘imageupload.html’ with context which contains the empty form.

Now create a folder template in your Django app ‘view_app’ and in that folder create a new file called imageupload.html and add the following lines of code.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload Files</title>
</head>

<body>
    <form method='post' enctype="multipart/form-data">
        {% csrf_token %}
        {{form.as_p}}
        <input type="submit" value="Submit">
    </form>
    {% if img_obj %}  
        <h3>Succesfully uploaded :</h3>  
        <img src="{{ img_obj.image.url}}" alt="connect" style="max-height:500px">  
    {% endif %}  
</body>

</html>
View Uploaded Files in Django Creating Template

In the above code look at lines from 17 to 10 where using the Django template to check if the img_obj exists or not that was passed through the view. If the img_obj exists, then it shows the two-element:

  • First, is the heading <h3> which shows the message ‘Successfully uploaded’ indicating that the image has been uploaded successfully.
  • Second, is the actual image which is uploaded using the Django template {{ img_obj.image.url}} within the <img> tag.
READ:  How to Convert a DataFrame to a Nested Dictionary in Python [4 Methods]

Also, install the package Pillow for processing the image using the below code.

pip install pillow
Installing Pillow How to View Uploaded Files in Django

View Uploaded Files in Django Migrating Model and Running Server

Open the terminal or command prompt and migrate the default database that comes with Django and the model ‘UploadImage’ that you have created. So run the below commands one by one in your terminal.

python manage.py migrate
python manage.py makemigrations
python manage.py migrate
View Uploaded Files in Django Migrating Model

Now run the below command to run the Django server.

python manage.py runserver

After running the server go to the URL ‘http://127.0.0.1:8000/upload’ and you see the page like this.

View Uploaded Files in Django Running Server

Now file the form or give the image title, upload the image and click on the Submit button as shown in the below picture.

view uploaded files at frontend using python django

As soon as you click on the Submit Button. The output will be as below.

Django view uploaded files at frontend example

In the above picture, you can see the uploaded image with the message ‘Successfully Upload’ and the picture of the uploaded file.

From here, we conclude that we can view the uploaded files from the browser’s front end.

Conclusion

In this Python Django tutorial, you learned how to view the uploaded files in Django, especially you learned how to view the image in the browser as soon as it is uploaded on the server. Additionally, you learn how you can pass the object to the template.

You may like to read: