Django-rest-framework, how to make model serializer fields mandatory

I have a model that I fill out step by step, this means that I am creating a form wizard.

Because of this, most of the fields in this model are required, but null=True, blank=True should be avoided so as not to create unnecessary errors when sending part of the data.

I work with Angular.js and django-rest-framework, and I need to tell api that the x and y fields should be required, and it needs to return a validation error if they are empty.

+7
python angularjs django django-rest-framework
source share
4 answers

You need to redefine the field and add your own validator. You can read here in more detail http://www.django-rest-framework.org/api-guide/serializers/#specifying-fields-explicitly . This is sample 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 
+5
source share

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

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

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

 from django.utils.translation import ugettext_lazy as _ from rest_framework.exceptions import ValidationError from rest_framework.utils.representation import smart_repr from rest_framework.compat import unicode_to_repr class 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) )) 

Using:

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

Another option is to use required and trim_whitespace if you are using CharField:

 class CustomObjectSerializer(serializers.Serializer): name = serializers.CharField(required=True, trim_whitespace=True) 

required doc: http://www.django-rest-framework.org/api-guide/fields/#required trim_whitespace doc: http://www.django-rest-framework.org/api-guide/fields/#charfield

+1
source share

All Articles