Skip to content
Related Articles

Related Articles

Improve Article
HiddenField in serializers – Django REST Framework
  • Last Updated : 27 Mar, 2020

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 HiddenField in Serializers in Django REST Framework.

HiddenField

HiddenField is a field class that does not take a value based on user input, but instead takes its value from a default value or callable.

Syntax –

field_name = serializers.HiddenField(*args, **kwargs)

Example –
For example, to include a field that always provides the current time as part of the serializer validated data, you would use the following:

modified = serializers.HiddenField(default=timezone.now)

The HiddenField class is usually only needed if you have some validation that needs to run based on some pre-provided field values, but you do not want to expose all of those fields to the end user.



How to use HiddenField in Serializers ?

To explain the usage of HiddenField, 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 HiddenField as the fields.




# import serializer from rest_framework
from rest_framework import serializers
  
class Geeks(object):
    def __init__(self, name, hidden):
        self.name = name
        self.hidden = hidden
  
# create a serializer
class GeeksSerializer(serializers.Serializer):
    # intialize fields
    name = serializers.CharField()
    hidden = serializers.HiddenField(default = 1)
     

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 a object of type Geeks
>>> obj = Geeks("Naveen", 999)

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

# print serialized data
>>> serializer.data
{'name': 'Naveen'}

Here is the output of all these operations on terminal –

hiddenfield-in-serializers-Django-REST-Framework

Validation on HiddenField

Note that prime motto of these fields is to impart validations, such as HiddenField validates the data to hidden object only. Let’s check if these validations are working or not –

# Create a dictionary and add values
>>> data = {}
>>> data['name'] = "Naveen"

# dictionary created
>>> data
{'name': 'Naveen'}

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

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

# check the errors
>>> serializer.errors
{}

Here is the output of these commands which clearly shows data valid even if hidden argument was not provided and it defaults to 1 –

hiddenfield-in-serializers

Advanced concepts

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.

Core arguments in serializer fields

ArgumentDescription
read_onlySet this to True to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization
write_onlySet this to True to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.
requiredSetting this to False also allows the object attribute or dictionary key to be omitted from output when serializing the instance.
defaultIf set, this gives the default value that will be used for the field if no input value is supplied.
allow_nullNormally an error will be raised if None is passed to a serializer field. Set this keyword argument to True if None should be considered a valid value.
sourceThe name of the attribute that will be used to populate the field.
validatorsA list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return.
error_messagesA dictionary of error codes to error messages.
labelA short text string that may be used as the name of the field in HTML form fields or other descriptive elements.
help_textA text string that may be used as a description of the field in HTML form fields or other descriptive elements.
initialA value that should be used for pre-populating the value of HTML form fields.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :