mandate integer type in django-rest-framework validator for integerfield

  • Last Update :
  • Techknowledgy :

Serializer keeps raw data in self.initial_data from where custom validation methods can retrieve it. So the following works

class Test(Serializer):
   true_int = IntegerField()

def validate_true_int(self, value):
   value = self.initial_data.get('true_int')
if isinstance(value, int):
   return value
raise ValidationError("Not an int")

data = {
   'true_int': '10'
}
t = Test(data = data)
t.is_valid() # false

data = {
   'true_int': 10
}
t = Test(data = data)
t.is_valid() # true

You can create a custom serializer field that errors before conversion to an integer.

class TrueIntegerField(serializers.IntegerField):
   def to_internal_value(self, data):
   if isinstance(data, six.text_type):
   raise serializers.ValidationError("Value should be an integer")
return super().to_internal_value(data)

You can write field validation

def validate_field_name(self):
   validating_data = self.context.get('request').data.get('field_name')
if isinstance(validating_data, int):
   return validating_data
raise ValidationError('Integer value required')

Suggestion : 2

You can create a custom serializer field anycodings_python that errors before conversion to an anycodings_python integer.,django-rest-framework validator accepts anycodings_django-rest-framework string quoted integers as valid data for anycodings_django-rest-framework integer field. Is there a way to mandate anycodings_django-rest-framework data type so that string quoted integers anycodings_django-rest-framework won't be accepted ?,Serializer keeps raw data in anycodings_python self.initial_data from where custom anycodings_python validation methods can retrieve it. So anycodings_python the following works,You can add a custom validator to the anycodings_python field. Custom Validator

Serializer keeps raw data in anycodings_python self.initial_data from where custom anycodings_python validation methods can retrieve it. So anycodings_python the following works

class Test(Serializer):
   true_int = IntegerField()

def validate_true_int(self, value):
   value = self.initial_data.get('true_int')
if isinstance(value, int):
   return value
raise ValidationError("Not an int")

data = {
   'true_int': '10'
}
t = Test(data = data)
t.is_valid() # false

data = {
   'true_int': 10
}
t = Test(data = data)
t.is_valid() # true

You can create a custom serializer field anycodings_python that errors before conversion to an anycodings_python integer.

class TrueIntegerField(serializers.IntegerField):
   def to_internal_value(self, data):
   if isinstance(data, six.text_type):
   raise serializers.ValidationError("Value should be an integer")
return super().to_internal_value(data)

You can write field validation

def validate_field_name(self):
   validating_data = self.context.get('request').data.get('field_name')
if isinstance(validating_data, int):
   return validating_data
raise ValidationError('Integer value required')

Suggestion : 3

Validators can be useful for re-using validation logic between different types of fields.,However, sometimes you'll want to place your validation logic into reusable components, so that it can easily be reused throughout your codebase. This can be achieved by using validator functions and validator classes.,Validation in Django REST framework serializers is handled a little differently to how validation works in Django's ModelForm class.,This validator can be used to enforce the unique=True constraint on model fields. It takes a single required argument, and an optional messages argument:

As an example of how REST framework uses explicit validation, we'll take a simple model class that has a field with a uniqueness constraint.

class CustomerReportRecord(models.Model):
   time_raised = models.DateTimeField(
      default = timezone.now, editable = False)
reference = models.CharField(unique = True, max_length = 20)
description = models.TextField()

Here's a basic ModelSerializer that we can use for creating or updating instances of CustomerReportRecord:

class CustomerReportSerializer(serializers.ModelSerializer):
   class Meta:
   model = CustomerReportRecord

If we open up the Django shell using manage.py shell we can now

>>> from project.example.serializers import CustomerReportSerializer
>>> serializer = CustomerReportSerializer()
>>> print(repr(serializer))
CustomerReportSerializer():
    id = IntegerField(label='ID', read_only=True)
    time_raised = DateTimeField(read_only=True)
    reference = CharField(max_length=20, validators=[<UniqueValidator(queryset=CustomerReportRecord.objects.all())>])
    description = CharField(style={'type': 'textarea'})

The validator should be applied to serializer classes, like so:

from rest_framework.validators
import UniqueTogetherValidator

class ExampleSerializer(serializers.Serializer):
   #...
   class Meta:
   # ToDo items belong to a parent list, and have an ordering defined
# by the 'position'
field.No two items in a given list may share
# the same position.
validators = [
   UniqueTogetherValidator(
      queryset = ToDoItem.objects.all(),
      fields = ['list', 'position']
   )
]

If you want the date field to be writable the only thing worth noting is that you should ensure that it is always available in the input data, either by setting a default argument, or by setting required=True.

published = serializers.DateTimeField(required = True)

Suggestion : 4

Mandate integer type in django-rest-framework validator for integerfield,how to create serializer for an enum field in django rest framework,How to support all REST operations for an endpoint in django rest framework,Django Rest Framework - Could not resolve URL for hyperlinked relationship using view name "user-detail"

Serializer keeps raw data in self.initial_data from where custom validation methods can retrieve it. So the following works

class Test(Serializer):
   true_int = IntegerField()

def validate_true_int(self, value):
   value = self.initial_data.get('true_int')
if isinstance(value, int):
   return value
raise ValidationError("Not an int")

data = {
   'true_int': '10'
}
t = Test(data = data)
t.is_valid() # false

data = {
   'true_int': 10
}
t = Test(data = data)
t.is_valid() # true

You can create a custom serializer field that errors before conversion to an integer.

class TrueIntegerField(serializers.IntegerField):
   def to_internal_value(self, data):
   if isinstance(data, six.text_type):
   raise serializers.ValidationError("Value should be an integer")
return super().to_internal_value(data)

You can write field validation

def validate_field_name(self):
   validating_data = self.context.get('request').data.get('field_name')
if isinstance(validating_data, int):
   return validating_data
raise ValidationError('Integer value required')

Suggestion : 5

Last Updated : 07 Jan, 2022

Syntax – 
 

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

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(123, 123.10, 123.123)

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

# print serialized data
   >>>
   serializer.data {
      'integer': 123,
      'float_number': 123.1,
      'decimal_number': '123.1230'
   }

Suggestion : 6

The serializers.py is very similar as the Form class file in Django, and including validation flags on the various fields, such as required, max_length and default. In the above code, we specified all the fields required, if any of the field is not provided by the user, it will throw an error. To avoid the error, we can pass the default value.,We have used the Modelserializer class, the same as the ModelForm class in Django. The serializers can also be created using the Serializers class.,We will create the serializers.py file in the sample_app, converting a model object into JSON format before sending the response.,We will use the APIView class, a subclass of Django's View class. We can define the get(), post(), patch(), and delete() methods so that we can perform the CRUD operations.

{
   "status": "error",
   "data": {
      "roll_number": [
         "A valid integer is required"
      ]
   }
}