Skip to content

Instantly share code, notes, and snippets.

@mrroot5
Forked from saadullahaleem/jsonschemafield.py
Last active April 1, 2020 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrroot5/4a7413bc335c67db7ee3c0448d3cff31 to your computer and use it in GitHub Desktop.
Save mrroot5/4a7413bc335c67db7ee3c0448d3cff31 to your computer and use it in GitHub Desktop.
Django json schema validator
import json
import os
from django.contrib.postgres.fields import JSONField
from django.core.exceptions import ValidationError
from django.utils.deconstruct import deconstructible
from jsonschema import validate, exceptions as jsonschema_exceptions
@deconstructible
class JSONSchemaValidator(JSONField):
def __init__(self, *args , **kwargs):
schema = kwargs.pop('schema', None)
if not schema:
raise ValueError('Schema is required')
if not isinstance(schema, str):
raise TypeError('Schema must be a path string, ex: "schemas/media_effects_jsonschema.json"')
self.schema = schema
super().__init__(*args, **kwargs)
@property
def _schema_data(self):
dirname = os.path.dirname(os.path.realpath(__file__))
p = os.path.join(dirname, self.schema)
with open(p, 'r') as read_file:
return json.loads(read_file.read())
def __call__(self, value):
try:
status = validate(json.loads(value), self._schema_data)
except jsonschema_exceptions.ValidationError as err:
error_msg = '{} {}.'.format(
self.error_messages.get('invalid', str(err)),
'Please check jsonschema'
)
raise ValidationError(error_msg)
except ValueError as err:
raise ValidationError('Field should be a valid json')
return status
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment