15
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
115
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}}
For this to work ensure that your models have been set as blank false null false as below.
some_field = models.CharField(blank=False, null=False, default='Anonymous')
- [Django]-How to get Request.User in Django-Rest-Framework serializer?
- [Django]-Factory-boy create a list of SubFactory for a Factory
- [Django]-Django Python rest framework, No 'Access-Control-Allow-Origin' header is present on the requested resource in chrome, works in firefox
9
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 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)
))
Usage:
class MyUserRegistrationSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ( 'email', 'first_name', 'password' )
validators = [
RequiredValidator(
fields=('email', 'first_name', 'password')
)
]
- [Django]-How to make the foreign key field optional in Django model?
- [Django]-Django how to partial render
- [Django]-How to delete old image when update ImageField?
7
This works very well on my backend app.
class SignupSerializer(serializers.ModelSerializer):
""" Serializer User Signup """
class Meta:
model = User
fields = ['username', 'password', 'password', 'first_name', 'last_name', 'email']
extra_kwargs = {'first_name': {'required': True, 'allow_blank': False}}
extra_kwargs = {'last_name': {'required': True,'allow_blank': False}}
extra_kwargs = {'email': {'required': True,'allow_blank': False}}
- [Django]-Exception: You cannot access body after reading from request's data stream
- [Django]-How can i test for an empty queryset in Django?
- [Django]-How can I use Bootstrap with Django?
3
According to link1 and link2, and due to the intended field is null=True, blank=True
(like email
field of django.contrib.auth.models.User
in my example) this will work:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'email', 'password')
extra_kwargs = {'email': {'required': True,
'allow_blank': False}}
- [Django]-Django development server, how to stop it when it run in background?
- [Django]-Using window functions in an update statement
- [Django]-Generating a Random Hex Color in Python
2
Another option is to use required
and trim_whitespace
if youโre using a 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
- [Django]-Django QuerySet order
- [Django]-How do I get the values of all selected checkboxes in a Django request.POST?
- [Django]-Do CSRF attacks apply to API's?