Skip to content

Instantly share code, notes, and snippets.

@saadullahaleem
Last active August 8, 2023 17:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save saadullahaleem/78603764a19441467e7988c9e5ed8bdf to your computer and use it in GitHub Desktop.
Save saadullahaleem/78603764a19441467e7988c9e5ed8bdf to your computer and use it in GitHub Desktop.
import inspect
from jsonschema import (
validate,
exceptions as jsonschema_exceptions
)
from django.core import exceptions
from django.contrib.postgres.fields import JSONField
class JSONSchemaField(JSONField):
def __init__(self, *args, **kwargs):
self.schema = kwargs.pop('schema', None)
super().__init__(*args, **kwargs)
@property
def _schema_data(self):
model_file = inspect.getfile(self.model)
dirname = os.path.dirname(model_file)
# schema file related to model.py path
p = os.path.join(dirname, self.schema)
with open(p, 'r') as file:
return json.loads(file.read())
def _validate_schema(self, value):
# Disable validation when migrations are faked
if self.model.__module__ == '__fake__':
return True
try:
status = validate(value, self._schema_data)
except jsonschema_exceptions.ValidationError as e:
raise exceptions.ValidationError(e.message, code='invalid')
return status
def validate(self, value, model_instance):
super().validate(value, model_instance)
self._validate_schema(value)
def pre_save(self, model_instance, add):
value = super().pre_save(model_instance, add)
if value and not self.null:
self._validate_schema(value)
return value
@mrroot5
Copy link

mrroot5 commented Mar 26, 2020

Which package is inspect?

I think it is from python:

import inspect

Because django inspect tell me that it doesn't have getfile method.

from django.utils import inspect

@saadullahaleem
Copy link
Author

saadullahaleem commented Mar 26, 2020

Which package is inspect?

I think it is from python:

import inspect

Because django inspect tell me that it doesn't have getfile method.

from django.utils import inspect

Yep. Its inspect from the standard library. Good catch!

@mrroot5
Copy link

mrroot5 commented Apr 1, 2020

I forked your gist to create a django validator instead of a JSONSchemaField:

https://gist.github.com/mrroot5/4a7413bc335c67db7ee3c0448d3cff31

Thanks a lot for your initial work :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment