Fixes #1489: Corrected server error on validation of empty required custom field

This commit is contained in:
Jeremy Stretch 2017-09-25 13:37:11 -04:00
parent a328e12642
commit 2badb04a03

View File

@ -29,34 +29,47 @@ class CustomFieldsSerializer(serializers.BaseSerializer):
for field_name, value in data.items(): for field_name, value in data.items():
cf = custom_fields[field_name] try:
cf = custom_fields[field_name]
except KeyError:
raise ValidationError(
"Invalid custom field for {} objects: {}".format(content_type, field_name)
)
# Validate custom field name # Data validation
if field_name not in custom_fields: if value not in [None, '']:
raise ValidationError("Invalid custom field for {} objects: {}".format(content_type, field_name))
# Validate boolean # Validate boolean
if cf.type == CF_TYPE_BOOLEAN and value not in [True, False, 1, 0]: if cf.type == CF_TYPE_BOOLEAN and value not in [True, False, 1, 0]:
raise ValidationError("Invalid value for boolean field {}: {}".format(field_name, value)) raise ValidationError(
"Invalid value for boolean field {}: {}".format(field_name, value)
)
# Validate date # Validate date
if cf.type == CF_TYPE_DATE: if cf.type == CF_TYPE_DATE:
try: try:
datetime.strptime(value, '%Y-%m-%d') datetime.strptime(value, '%Y-%m-%d')
except ValueError: except ValueError:
raise ValidationError("Invalid date for field {}: {}. (Required format is YYYY-MM-DD.)".format( raise ValidationError(
field_name, value "Invalid date for field {}: {}. (Required format is YYYY-MM-DD.)".format(field_name, value)
)) )
# Validate selected choice # Validate selected choice
if cf.type == CF_TYPE_SELECT: if cf.type == CF_TYPE_SELECT:
try: try:
value = int(value) value = int(value)
except ValueError: except ValueError:
raise ValidationError("{}: Choice selections must be passed as integers.".format(field_name)) raise ValidationError(
valid_choices = [c.pk for c in cf.choices.all()] "{}: Choice selections must be passed as integers.".format(field_name)
if value not in valid_choices: )
raise ValidationError("Invalid choice for field {}: {}".format(field_name, value)) valid_choices = [c.pk for c in cf.choices.all()]
if value not in valid_choices:
raise ValidationError(
"Invalid choice for field {}: {}".format(field_name, value)
)
elif cf.required:
raise ValidationError("Required field {} cannot be empty.".format(field_name))
# Check for missing required fields # Check for missing required fields
missing_fields = [] missing_fields = []