File upload Fields in Serializers - Django REST Framework - GeeksforGeeks

20 Dec, 2021
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField, CharField and BooleanField for storing and manipulating data through Django. Similarly, serializer also works with same principle and has fields that are used to create a serializer. This article revolves around File Upload Fields Fields in Serializers in Django REST Framework. There are two major fields – FileField and ImageField. 
FileField is basically a file representation. It performs Django’s standard FileField validation. This field is same as FileField – Django Models.It has the following arguments –  
max_length – Designates the maximum length for the file name.
allow_empty_file – Designates if empty files are allowed.
use_url – If set to True then URL string values will be used for the output representation. If set to False then filename string values will be used for the output representation. Defaults to the value of the UPLOADED_FILES_USE_URL settings key, which is True unless set otherwise.
Syntax – 
field_name = serializers.FileField(*args, **kwargs) 
ImageField is an image representation.It validates the uploaded file content as matching a known image format. This is same as ImageField – Django formsIt has the following arguments –  
max_length – Designates the maximum length for the file name.
allow_empty_file – Designates if empty files are allowed.
use_url – If set to True then URL string values will be used for the output representation. If set to False then filename string values will be used for the output representation. Defaults to the value of the UPLOADED_FILES_USE_URL settings key, which is True unless set otherwise.
Syntax – 
field_name = serializers.ImageField(*args, **kwargs) 
To explain the usage of file upload Fields, let’s use the same project setup from – How to Create a basic API using Django Rest Framework ?. Now that you have a file called serializers in your project, let’s create a serializer with FileField and ImageField as the fields. 
Python3
# import serializer from rest_frameworkfrom rest_framework import serializers class Geeks(object):    def __init__(self, files, image):        self.files = files        self.image = image # create a serializerclass GeeksSerializer(serializers.Serializer):    # initialize fields    files = serializers.FileField()    image = serializers.ImageField()
Now let us create some objects and try serializing them and check if they are actually working, Run, –  
Python manage.py shell
Now, run following python commands in the shell 
# import everything from serializers
>>> from apis.serializers import *

# create objects of type Text File and Image
>>> from django.core.files import File
>>> text_file = File(open("test.txt"), 'rb')
>>> image_file = File(open("test.jpeg"), 'rb')

# create a object of type Geeks
>>> obj = Geeks(text_file, image_file)

# serialize the object
>>> serializer = GeeksSerializer(obj)

# print serialized data
>>> serializer.data
{'files': None, 'image': None}
Here is the output of all these operations on terminal – 
Note that prime motto of these fields is to impart validations, such as Filefield validates the data to file only. Let’s check if these validations are working or not – 
# Create a dictionary and add invalid values
>>> data = {}
>>> data['files'] = text_file
>>> data['image_file'] = "invalid"

# dictionary created
>>> data
{'files': , 'image_file': 'invalid'}

# deserialize the data
>>> serializer = GeeksSerializer(data=data)

# check if data is valid
>>> serializer.is_valid()
False

# check the errors
>>> serializer.errors
{'image': [ErrorDetail(string='No file was submitted.', code='required')]}
Here is the output of these commands which clearly shows image as invalid and file as valid – 
Validations are part of Deserialization and not serialization. As explained earlier, serializing is process of converting already made data into another data type, so there is no requirement of these default validations out there. Deserialization requires validations as data needs to be saved to database or any more operation as specified. So if you serialize data using these fields that would work. 
.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; }  
surinderdawra388
Django-REST
Python Django
rest-framework
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python