Search code examples
djangodjango-rest-frameworkdjango-serializer

How to add required field blank field in serializers?


I need to add that field should be added compulsory in serializers how to do that?

from rest_framework import serializers
from django.contrib.auth.models import User


class SignUpSerializer(serializers.Serializer):

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'password')

I'm expecting some kind of validators to validate those fields


Solution

  • You can use keyword args function to validate like

    class SignUpSerializer(serializers.Serializer):
    
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'password')
    
        extra_kwargs = {
            'first_name':{'required':True, 'allow_blank':False},
            'last_name':{'required':True, 'allow_blank':False},
            'email':{'required':True, 'allow_blank':False}
        }