Last active
August 8, 2023 17:45
-
-
Save saadullahaleem/78603764a19441467e7988c9e5ed8bdf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Which package is inspect?
I think it is from python:
import inspectBecause 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!
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
Which package is inspect?
I think it is from python:
Because django inspect tell me that it doesn't have
getfile
method.