Updated May 3, 2023
Introduction to Django File Upload
Every web application will have form processing within it; uploading files as a part of the form processing is a very common operation. Correctly uploading these files is crucial for processing the form. This file upload processing in Django discusses all methods involved as a part of the file-level processing in Django. The files uploaded can be retrieved, processed, stored, etc. Libraries like storage and file system storage are beneficial in the file upload process for storage-level necessities. These file fields used for file upload in Django evolved from the forms processing section of the Django framework.
SETTING File Upload
In Django, the FILES[] function tags the request with the uploaded file. The request. Files are responsible for capturing the uploaded file details and keeping them tagged within it. The uploaded file details and contents need to be retrieved from this request. Files[] section and then furtherly processed by mentioning the request.FILES with reference to the file name, will create the object used to act more as a file-based object in the file setup and storage process. You can retrieve all the details regarding the file from this file-based object.
How to Upload Django File?
The file upload process consists of the below significant steps; Let’s go through the step-by-step process of how Django handles file uploads.
1. Declare the file field in the Forms.py file. To process the file as a form template, we import the important FileField() class from the forms library. The object created for these elements will act as the file field object. In the below example, it is represented as ‘uploaded_File’.
#-*- coding: utf-8 -*-
from django import forms
class fileform(forms.Form):
Uploaded_File = forms.FileField()
2. Create the view for processing the file; this view is the most critical section in rendering and processing the file. Here the above-created field will be. While creating this view, the key points need to be taken into accountability.
3. The uploaded file will be tagged as a part of the request. Files, All details regarding the file and file can be processed using this request. Files section. The file can be captured into a file-based object using the below line,
uploaded_file = request.FILES['Uploaded_File']
4. To access the file and details regarding the file, the below methods can be used, So all operations on the file, like the determination of file size, determination of name of the file, Also identifying the content type of the file, which is tagged to the requested file and even reading the file can be accomplished by these methods, there are also methods named as chunks which help read the file as smaller chunks.
5. Methods of Django File Upload
Below are the methods and its description of Django File Upload:
Method | Description |
UploadedFile.name | Displays the name of the uploaded file. |
UploadedFile.size | Displays the size of the uploaded file. |
UploadedFile.content_type | Mentions the type of content being handled by the file. |
UploadedFile.content_type_extra | Mentions the additional headers associated with the content type. |
UploadedFile.charset | Mentions the character set supplied by the browser |
UploadedFile.read() | This method is used to read the entire data from the file. |
6. The FileSystemStorage class can be used for performing basic file storage operations on the filesystem of the local area.
Syntax:
FileSystemStorage(location, base_url, file_permissions_mode, directory_permissions_mode)
Argument | Description |
Location | This represents the directory in which the file is stored |
base_url | URL of the location at which the file is stored |
file_permissions_mode | permission associated with the file |
directory_permissions_mode | The file system permissions that the directory will receive when it is saved. |
7. The view below shows all file-level operations performed on this file. Let me clarify the process of the view. We start by creating an object for the form file. Then, we reference the field in the model file to retrieve the message from the request.files[] header. Once we have assigned request.FILES to an object, we can select a file and use the request.file method of the associated object to perform all further actions. This method is responsible for identifying important information about the file, such as its size, content header, and filename.
Code:
Views.py
from django.shortcuts import render
from django.http import HttpResponse
from Django_app1.forms import fileform
from django.contrib.auth.models import User
from django.core.files.storage import FileSystemStorage
from django.contrib import messages
def file_upload(request):
file = fileform()
print(" File Values in File Dictionary:", request.FILES)
if request.method == 'POST' and request.FILES['Uploaded_File']:
uploaded_file = request.FILES['Uploaded_File']
fs = FileSystemStorage()
filename = fs.save(uploaded_file.name, uploaded_file)
uploaded_File_Size = 'Size of Uploaded file: ' + str(uploaded_file.size)
content_type_of_uploaded_file = 'Content type of uploaded file: ' + str(uploaded_file.content_type)
uploaded_file_name = 'Name of Uploaded file: ' + str(uploaded_file.name)
uploaded_file_url = fs.url(filename)
print("uploaded file url",uploaded_file_url)
messages.success(request, '!!! File upload successful !!!')
messages.success(request,uploaded_File_Size)
messages.success(request,uploaded_file_name)
messages.success(request,content_type_of_uploaded_file)
return render(request, 'filehandeling.html', {"file":file})
return render(request, 'filehandeling.html',{"file":file})
8. I need to create the file upload field by making an HTML template and utilizing the code snippet provided in the forms.py section of the application. The HTML file additionally includes code for displaying the messages triggered as a part of the file upload process.
Message Framework Methods:
- messages.debug(request, ‘Intended message’)
- messages.info(request,’Intended message’)
- messages.success(request,’Intended message’)
- messages.warning(request, ‘Intended message’)
- messages.error(request, ‘Intended message’)
Code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Django App1</title>
</head>
<body>
<h1> <u> FILE UPLOAD HANDELING IN DJANGO </u> </h1>
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
<div style = "max-width:470px;">
<form method = 'POST' enctype="multipart/form-data">
{{ file.as_p }}
{% csrf_token %}
<input type="submit" class="btn btn-primary" value="submit">
</form>
</div>
</body>
</html>
Output:
Conclusion
From the above examples, we can notice how flexibly the file-level processing can be achieved from a Django framework from the available set of methods.
Recommended Articles
We hope that this EDUCBA information on “Django File Upload” was beneficial to you. You can view EDUCBA’s recommended articles for more information.