django-rest-framework 如何使模型序列化程序字段成为必需的
django-rest-framework how to make model serializer fields required
我有一个正在逐步填写的模型,这意味着我正在制作一个表单向导。
因为此模型中的大多数字段都是必需的,但有 null=True, blank=True
以避免在提交部分数据时引发非空错误。
我正在使用 Angular.js 和 django-rest-framework,我需要告诉 api 应该需要 x 和 y 字段并且它需要 return 如果它们为空,则验证错误。
您需要专门覆盖该字段并添加您自己的验证器。您可以在此处阅读更多详细信息 http://www.django-rest-framework.org/api-guide/serializers/#specifying-fields-explicitly。这是示例代码。
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
这是我的多领域方式。它基于重写 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)
))
用法:
class MyUserRegistrationSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ( 'email', 'first_name', 'password' )
validators = [
RequiredValidator(
fields=('email', 'first_name', 'password')
)
]
根据文档 here 的最佳选择是在 class 元中使用 extra_kwargs,例如,您有存储 phone 号码的 UserProfile 模型并且是必需的
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ('phone_number',)
extra_kwargs = {'phone_number': {'required': True}}
另一种选择是使用 required
和 trim_whitespace
如果您使用的是 CharField:
class CustomObjectSerializer(serializers.Serializer):
name = serializers.CharField(required=True, trim_whitespace=True)
required
文档:http://www.django-rest-framework.org/api-guide/fields/#required
trim_whitespace
文档:http://www.django-rest-framework.org/api-guide/fields/#charfield
根据 link1 and link2,并且由于预期的字段是 null=True, blank=True
(就像我的示例中 django.contrib.auth.models.User
的 email
字段)这将起作用:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'email', 'password')
extra_kwargs = {'email': {'required': True,
'allow_blank': False}}
这在我的后端应用程序上运行良好。
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}}
我有一个正在逐步填写的模型,这意味着我正在制作一个表单向导。
因为此模型中的大多数字段都是必需的,但有 null=True, blank=True
以避免在提交部分数据时引发非空错误。
我正在使用 Angular.js 和 django-rest-framework,我需要告诉 api 应该需要 x 和 y 字段并且它需要 return 如果它们为空,则验证错误。
您需要专门覆盖该字段并添加您自己的验证器。您可以在此处阅读更多详细信息 http://www.django-rest-framework.org/api-guide/serializers/#specifying-fields-explicitly。这是示例代码。
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
这是我的多领域方式。它基于重写 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)
))
用法:
class MyUserRegistrationSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ( 'email', 'first_name', 'password' )
validators = [
RequiredValidator(
fields=('email', 'first_name', 'password')
)
]
根据文档 here 的最佳选择是在 class 元中使用 extra_kwargs,例如,您有存储 phone 号码的 UserProfile 模型并且是必需的
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ('phone_number',)
extra_kwargs = {'phone_number': {'required': True}}
另一种选择是使用 required
和 trim_whitespace
如果您使用的是 CharField:
class CustomObjectSerializer(serializers.Serializer):
name = serializers.CharField(required=True, trim_whitespace=True)
required
文档:http://www.django-rest-framework.org/api-guide/fields/#required
trim_whitespace
文档:http://www.django-rest-framework.org/api-guide/fields/#charfield
根据 link1 and link2,并且由于预期的字段是 null=True, blank=True
(就像我的示例中 django.contrib.auth.models.User
的 email
字段)这将起作用:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'email', 'password')
extra_kwargs = {'email': {'required': True,
'allow_blank': False}}
这在我的后端应用程序上运行良好。
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}}