Upload a file in Django

In this tutorial, we will be talking about how to upload a file in Django.

The question is why we need to do so when we already have CharField(), IntegerField(), TextField() but sometimes we need to upload files like an image or a pdf or some file in some other format like if you want to add a profile picture in Facebook, you need to upload a file. We will be able to upload a file and view it by the end of this tutorial.

I hope you know how to start a project and app in Django. My project name is project and my app name is fileupload, you too can name your project and app by the same name.

Steps to upload a file in Django

The very first step towards our task is to create templates and urls.py files under our app. Once you have created these two files, you need to redirect the user to another page which we will mention in urls.py of our app. To redirect, open urls.py of your project and add path('',include("fileupload.urls"),. Also, don’t forget to import include from django.urls.

urls.py of our project would look like:

from django.contrib import admin
from django.urls import path,include

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

Open urls.py of your app and write the below code in that file:

from django.urls import path
from fileupload.views import home
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
    path('',home)
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

Now create index.html in the templates folder just created. This will contain the details we want to display on our page where we will upload our file. This is the code for index.html, I have done a bit of styling you can skip it too by removing the <style> section inside the header.

 

<!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>Document</title>
    <style>
        body
        {
            background-color: blanchedalmond;
            text-align: center;
            
        }
        .button
        {
            background-color: chocolate;
            padding: 17px 34px;
            text-align: center;
            font-size: 16px;
            margin: 5px;
        }
        
    </style>
</head>
<body>
    <div class="container">
        <form method="post" enctype="multipart/form-data">
            {% csrf_token %}
            <input type="file" class="button" name="file">
            <br>
            <input type="submit" class="button">
        </form>
    </div>
</body>
</html>

Install your app in installed apps under settings.py in your project. You just need to add your app name at the end of installed apps like:

 

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'fileupload',
]

We need to mention MEDIA_URL and MEDIA_ROOT in the settings.py to save and serve the media files uploaded.

 

MEDIA_ROOT=os.path.join(BASE_DIR,"media")
MEDIA_URL='/media/'

Don’t forget to import os.

Let’s create our model now:

class file_upload(models.Model):
    file=models.FileField()

Now we need to make changes in views.py present inside our app

from django.http import HttpResponse
from django.shortcuts import render,HttpResponse
from fileupload.models import file_upload
# Create your views here.
def home(request):
    if request.method=="POST":
        file1=request.FILES["file"]
        document=file_upload.objects.create(file=file1)
        document.save()
        return HttpResponse("Upload was successful")
    return render(request,"index.html")

This will save files that we will be able to view, but first, we need to createsuperuser. To do this write python manage.py createsuperuserin your terminal.

It will ask you for some basic details which will be used later to log in to Django Administrator.

We are just a few steps away to upload and viewing our file. Without any further delay open your admin.py import file_upload using from .models import file_upload and register your model using admin.site.register(file_upload)

Okay, so let’s migrate the changes we have made. You guessed it right. We will execute two commands in the terminal-

python manage.py makemigrations

python manage.py migrate

This will migrate and save our changes permanently to the database.

Upload file

We are all set to upload our file.

Run your server using-python manage.py runserver

Now navigate to the URL – http://127.0.0.1:8000/

You will be able to see a page like-

Upload a file in Django

Select a file from your computer then hit submit.

You will see a browser window like-

Upload a file in Django

View the file uploaded

As the file is uploaded, now we can see what was uploaded. It is very very simple, you just need to navigate into http://127.0.0.1:8000/admin

Log in to the Django Administration using the credentials you have created. You will be able to see file_uploads, open and then click on the file_upload object(1), now click on the file name you have uploaded, the file will be opened.

Also, you can view it in the file explorer in the media folder.

We have just completed our task on how to upload a file in Django. I hope you like this tutorial, feel free to comment and share your reviews.

KEEP READING! KEEP CODING!

Leave a Reply

Your email address will not be published.