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. the method through which these files uploaded as a part of form processing is critical. 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 retrived, processed, stored, etc. libraries like storage and file system storage are very helpful in the file upload process for storage level necessities. These file fields used for file upload in Django are evolved from the forms processing section of the Django framework.
SETTING File Upload
When a file is uploaded in Django the file is tagged to the request through request.Files[]. Thes request. Files are responsible for capturing the file details being uploaded and keep 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, this will be creating the object which is used to be acting more as like a file-based object in the file setup and storage process. All details regarding the file could be pulled from this file-based object.
How to Upload Django File?
Basically the file upload process consists of below major steps, The below-derived steps is a step by step process of how the file processing during the file upload is achieved in Django.
1. Declare the file field in the Forms.py file. This is the more critical part because this field will be used as a reference for representing the file in the template being used for processing the form. here the forms library is used for importing the FileField() class, the object created for these elements will be acting as the object for the file field. 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 below 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 itself can be processed using this request. Files section. The file can be captured into a file-based object by means of 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 are useful in reading 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 to 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 to the file |
directory_permissions_mode | The file system permissions that the directory will receive when it is saved. |
7. The below view shows all file-level operations being performed on this file. the process involved in the view are explained below. First, the object for the form file is created. The model file field is used as a reference for retrieving the message from the request.files[] header. The request.FILES is assigned to an object. This object is used for all further operations on the file. So the process of identifying the file size, content header, filename, etc are achieved from this object associated to request.file method.
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. The HTML template for the file needs to be formulated, in the below-shown code snippet, the file upload field is rendered from the forms.py section of the application. The HTML file additionally includes code for displaying the messages which are 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
We can notice from the above-given examples that how flexibly the file level processing can be achieved from a Django framework from the available set of methods.