django-rest-framework how to make model serializer fields required django-rest-framework how to make model serializer fields required angularjs angularjs

django-rest-framework how to make model serializer fields required


The best option according to docs here is to use extra_kwargs in class Meta, For example you have UserProfile model that stores phone number and is required

class UserProfileSerializer(serializers.ModelSerializer):    class Meta:        model = UserProfile        fields = ('phone_number',)        extra_kwargs = {'phone_number': {'required': True}} 


You need to override the field specifically and add your own validator. You can read here for more detail http://www.django-rest-framework.org/api-guide/serializers/#specifying-fields-explicitly. This is the example code.

def required(value):    if value is None:        raise serializers.ValidationError('This field is required')class GameRecord(serializers.ModelSerializer):    score = IntegerField(validators=[required])    class Meta:        model = Game


This is my way for multiple fields. It based on rewriting UniqueTogetherValidator.

from django.utils.translation import ugettext_lazy as _from rest_framework.exceptions import ValidationErrorfrom rest_framework.utils.representation import smart_reprfrom rest_framework.compat import unicode_to_reprclass RequiredValidator(object):    missing_message = _('This field is required')    def __init__(self, fields):        self.fields = fields    def enforce_required_fields(self, attrs):        missing = dict([            (field_name, self.missing_message)            for field_name in self.fields            if field_name not in attrs        ])        if missing:            raise ValidationError(missing)    def __call__(self, attrs):        self.enforce_required_fields(attrs)    def __repr__(self):        return unicode_to_repr('<%s(fields=%s)>' % (            self.__class__.__name__,            smart_repr(self.fields)        ))

Usage:

class MyUserRegistrationSerializer(serializers.ModelSerializer):    class Meta:        model = User        fields = ( 'email', 'first_name', 'password' )        validators = [            RequiredValidator(                fields=('email', 'first_name', 'password')            )        ]