bhch / django-jsonform

A better, user-friendly JSON editing form field for Django admin. Also supports Postgres ArrayField.
https://django-jsonform.rtfd.io
BSD 3-Clause "New" or "Revised" License
307 stars 31 forks source link

Custom validation of object properties not showing error next to field #141

Closed captain828 closed 5 months ago

captain828 commented 5 months ago

Schema:

{
    'type': 'object',
    'properties': {
        'my_prop': {
            'type': 'string',
            'helpText': 'Some help text.',
            'required': True
        }
    }
}

Custom validation inside model:

def clean(self):
  error_map = ErrorMap()
  key = 'my_prop'
  url = self.config[key]
  try:
      URLValidator()(url)
  except ValidationError:
      error_message = _('URL is invalid')
      error_map.set(coords=[key], msg=error_message)
      raise JSONSchemaValidationError(
          error_message,
          error_map=error_map
      )

Tests:

Expected result:

Versions:


The only thing I can think of is that coords=[key] isn't correct but the docs don't cover this simple case (they focus on an array with an object inside) and all the other ways I've tried didn't work.

bhch commented 5 months ago

Doing this inside a model's clean method isn't possible because then the validation will be handled by the model (not the json field). So the model doesn't pass the error_map object over to the json field.

What we want to do is to make this validation at the field level. So that field can catch the exception early and use the error_map.

So, you are required to create a custom form for this and set a custom validator on the json field. See docs: https://django-jsonform.readthedocs.io/en/latest/guide/validation.html#creating-a-form

captain828 commented 5 months ago

Awesome, thanks for clarifying!