From aa6749dae7b1598095fa180f3883c8082a39a10b Mon Sep 17 00:00:00 2001 From: Jeremy Stretch Date: Mon, 25 Sep 2017 13:37:11 -0400 Subject: [PATCH] Fixes #1489: Corrected server error on validation of empty required custom field --- netbox/extras/api/customfields.py | 69 ++++++++++++++++++------------- 1 file changed, 41 insertions(+), 28 deletions(-) diff --git a/netbox/extras/api/customfields.py b/netbox/extras/api/customfields.py index fc83b33e575..5554df924da 100644 --- a/netbox/extras/api/customfields.py +++ b/netbox/extras/api/customfields.py @@ -29,34 +29,47 @@ def to_internal_value(self, data): for field_name, value in data.items(): - cf = custom_fields[field_name] - - # Validate custom field name - if field_name not in custom_fields: - raise ValidationError("Invalid custom field for {} objects: {}".format(content_type, field_name)) - - # Validate boolean - 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)) - - # Validate date - if cf.type == CF_TYPE_DATE: - try: - datetime.strptime(value, '%Y-%m-%d') - except ValueError: - raise ValidationError("Invalid date for field {}: {}. (Required format is YYYY-MM-DD.)".format( - field_name, value - )) - - # Validate selected choice - if cf.type == CF_TYPE_SELECT: - try: - value = int(value) - except ValueError: - raise ValidationError("{}: Choice selections must be passed as integers.".format(field_name)) - 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)) + try: + cf = custom_fields[field_name] + except KeyError: + raise ValidationError( + "Invalid custom field for {} objects: {}".format(content_type, field_name) + ) + + # Data validation + if value not in [None, '']: + + # Validate boolean + 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) + ) + + # Validate date + if cf.type == CF_TYPE_DATE: + try: + datetime.strptime(value, '%Y-%m-%d') + except ValueError: + raise ValidationError( + "Invalid date for field {}: {}. (Required format is YYYY-MM-DD.)".format(field_name, value) + ) + + # Validate selected choice + if cf.type == CF_TYPE_SELECT: + try: + value = int(value) + except ValueError: + raise ValidationError( + "{}: Choice selections must be passed as integers.".format(field_name) + ) + 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 missing_fields = []