0
0
Djangoframework~5 mins

Serializer validation in Django

Choose your learning style9 modes available
Introduction

Serializer validation helps check if the data sent to your Django app is correct and safe before saving or using it.

When you receive data from a user through an API and want to make sure it follows rules.
When you want to give clear error messages if the data is missing or wrong.
When you need to clean or change data before saving it to the database.
When you want to check complex conditions that simple field types can't handle.
When you want to keep your app safe from bad or harmful data.
Syntax
Django
from rest_framework import serializers

class MySerializer(serializers.Serializer):
    field_name = serializers.CharField(max_length=100)

    def validate_field_name(self, value):
        # custom validation for field_name
        if 'bad' in value:
            raise serializers.ValidationError("No 'bad' allowed!")
        return value

    def validate(self, data):
        # validation for multiple fields together
        if data.get('field_name') == 'forbidden':
            raise serializers.ValidationError("This value is forbidden.")
        return data

validate_field_name checks one field at a time.

validate checks the whole data dictionary for rules involving multiple fields.

Examples
This example checks that the username has no spaces.
Django
class UserSerializer(serializers.Serializer):
    username = serializers.CharField()

    def validate_username(self, value):
        if ' ' in value:
            raise serializers.ValidationError("Username cannot contain spaces.")
        return value
This example checks that discount is not greater than price by validating multiple fields together.
Django
class ProductSerializer(serializers.Serializer):
    price = serializers.FloatField()
    discount = serializers.FloatField()

    def validate(self, data):
        if data['discount'] > data['price']:
            raise serializers.ValidationError("Discount cannot be more than price.")
        return data
Sample Program

This serializer checks that pages is positive and title is not the same as author (case insensitive). It prints errors if validation fails.

Django
from rest_framework import serializers

class BookSerializer(serializers.Serializer):
    title = serializers.CharField(max_length=50)
    author = serializers.CharField(max_length=50)
    pages = serializers.IntegerField()

    def validate_pages(self, value):
        if value <= 0:
            raise serializers.ValidationError("Pages must be a positive number.")
        return value

    def validate(self, data):
        if data['title'].lower() == data['author'].lower():
            raise serializers.ValidationError("Title and author cannot be the same.")
        return data

# Example usage
serializer = BookSerializer(data={
    'title': 'Django Basics',
    'author': 'django basics',
    'pages': 100
})

if not serializer.is_valid():
    print(serializer.errors)
else:
    print("Data is valid")
OutputSuccess
Important Notes

Always call is_valid() before accessing validated data or saving.

Field-level validation methods must be named validate_.

Use validate() for rules involving multiple fields.

Summary

Serializer validation checks data correctness before use.

Use validate_<field> for single fields and validate() for multiple fields.

Validation errors help give clear feedback to users or API clients.