top of page

Django File Uploads: Simplified

Updated: Apr 27, 2023

INTRODUCTION

In this session, we will learn how to upload files in Django.

First we will create a project name "file_upload". To do this, we will write this on the command prompt or on the VS Code terminal,


django manage.py startapp <app name>


In our case it is file_upload and therefore we will write,

django manage.py startapp file_upload


After doing that, a folder will get created in the working directory. The directory will contains files like apps.py, admin.py, test.py.


We will need to create new files and directory in the folder.


Now, as the new app has been created, we need to update the setting.py file to make sure Django recognizes the existence of the app. To do this we will open the settings.py file and look for the list named INSTALLED_APPS.


To include the app into the list, we will add its name into the list.


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

    'file_upload',
]

Now, we will create some files in the directory of named "file_upload". The files are,

The file file that we will create is models.py. In Django, models.py is a file that defines the structure of the database tables used by your web application. It is a Python module that contains classes representing database tables, each of which inherits from Django's built-in models.Model class.

The models.py file defines the database schema for your web application and serves as the blueprint for the database tables that your application will use. It specifies the fields and their types, as well as any additional metadata, such as verbose names, default values, and help texts.

By defining your database schema in models.py, Django can automatically generate the necessary database tables, indexes, and relationships based on your model classes. This makes it easy to manage and maintain your database, and allows you to interact with it using Python code.

In addition, models.py also allows you to define custom methods and properties for your model classes, and can be used to implement advanced features such as validation, form handling, and complex data queries.


Now we will add this script in the model.py file:

from django.db import models

class UserFile(models.Model):
    name = models.CharField(max_length=255)
    email = models.EmailField()
    file = models.FileField(upload_to='uploads/')

Now, we will create a folder named templates, and then inside that template, we will create another folder that is similar to the name of the app. In our case it is file_upload.

So the path of the directory from the app will be file_upload/templates/file_upload. In this folder, we will create the HTML files that we want to show on the browser.

The HTML file will be like this:



In the folder, we will create a file named as upload.html, and inside that file, we will write:



<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>File Upload</title>
</head>
<body>
    <h1>Upload a File</h1>
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Upload">
    </form>
</body>
</html>

Now, that we have created html file, we will now create a file name views.py. In Django, views.py is a file that contains the Python code that handles HTTP requests and returns HTTP responses. It defines the functions, called views, that are responsible for processing requests from the web browser and returning a response to the user.


Views are Django's way of implementing the controller logic in the Model-View-Controller (MVC) architectural pattern. They serve as the intermediary between the data (stored in the database) and the user interface (displayed in the browser).


Each view is a Python function that takes an HTTP request object as its argument and returns an HTTP response object. The view function can perform a variety of tasks, such as querying the database, processing form data, generating HTML templates, and rendering dynamic content.


The views.py file typically contains a set of view functions, each mapped to a specific URL pattern. When a user makes a request to a URL that matches a pattern defined in the urls.py file, Django dispatches the request to the appropriate view function to generate the response.


In addition, views.py can also contain helper functions and utility classes that are used by the views to perform specific tasks, such as authentication, authorization, and validation.


We will add this script to the file:


from django.shortcuts import render, redirect
from .forms import UserFileForm

def upload_file_view(request):
    if request.method == 'POST':
        form = UserFileForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return render(request, 'file_upload/upload.html', {'form': form})
    else:
        form = UserFileForm()
    return render(request, 'file_upload/upload.html', {'form': form})

After doing this we will create a folder named as urls.py. In Django, urls.py is a file that defines the mapping between URLs and views in your web application. It is used to specify which views should be called for each URL pattern and provides a way to map URLs to specific Python functions.


The main purpose of creating urls.py is to provide a central place to manage the URLs of your web application. It allows you to define the URLs that users can enter to access different parts of your site and to specify which view function should handle each URL.


By separating URL mapping from view functions, urls.py provides greater flexibility and maintainability to your web application. It also makes it easier to manage complex URL patterns, such as those that include query parameters, regular expressions, or multiple parameters.


In addition, urls.py also provides a way to organize your web application into different modules or apps. Each app can have its own urls.py file that defines the URLs and views specific to that app.


This makes it easier to reuse and distribute your code and to maintain a clear separation of concerns between different parts of your web application.

Overall, urls.py is an essential file in Django that plays a key role in defining the structure and behavior of your web application's URLs and views.

from django.urls import path
from file_upload.views import upload_file_view

app_name = 'file_upload'

urlpatterns = [
    path('upload/', upload_file_view, name='upload_file'),
]

Now, there is a file named admin.py in the app directory. We will add this script to the file so that the information, that are mentioned in the form, will be written on the server:
from django.contrib import admin

# Register your models here.
from .models import UserFile

admin.site.register(UserFile)

After doing this, we will run the following commands,

python manage.py makemigrations
python manage.py migrate

After doing this, we will run the server if it is not already running by giving the command,

python manage.py runserver

The, we will enter the the address http://127.0.0.1:8000/upload/ in the web browser to open the upload form.


After filling this form, the uploaded file will be saved in the folder named upload that is in the folder name "media". This folder is in the folder src.


To view the uploaded file in the server, we have to visit the URL http://127.0.0.1:8000/admin/


Now we have to enter the credentials that we have created throught the command

python manage.py createsuperuser


After doing that, we have to click on the tab named User files that has created an instance for the first uploaded first.




Final arrangements of files and folder is like this,


If you require any assistance with your Django projects, please do not hesitate to contact us. We have a team of experienced developers who specialize in Django and can provide you with the necessary support and expertise to ensure the success of your project. You can reach us through our website or by contacting us directly via email or phone. We look forward to hearing from you and helping you with your Django development needs.



Comments


bottom of page