Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,3 +118,4 @@ Need help integrating, customizing, or scaling Django Admin with Unfold?
- **Range Slider**: [noUiSlider](https://github.com/leongersen/noUiSlider) - Licensed under the [MIT License](https://opensource.org/licenses/MIT).
- **Number Formatting**: [wNumb](https://github.com/leongersen/wnumb) - Licensed under the [MIT License](https://opensource.org/licenses/MIT).
- **WYSIWYG Editor**: [Trix](https://github.com/basecamp/trix) - Licensed under the [MIT License](https://opensource.org/licenses/MIT).
- **JSON Schema Editor**: [Jedison](https://github.com/germanbisurgi/jedison) - Licensed under the [MIT License](https://opensource.org/licenses/MIT).
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,16 +44,17 @@ dev = [
"django-money==3.6.0",
"django-simple-history==3.11.0",
"django-stubs==6.0.3",
"jsonschema==4.26.0",
"pillow==12.2.0",
"pytest==9.0.3",
"pytest-cov==7.1.0",
"pytest-django==4.12.0",
"pytest-factoryboy==2.8.1",
"pytest-mock==3.15.1",
"python-semantic-release==10.5.3",
"tox==4.53.0",
"six==1.17.0",
"psycopg[binary]==3.3.4",
"tox==4.53.0",
]

[tool.uv]
Expand Down
12 changes: 12 additions & 0 deletions src/unfold/fields.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from typing import TYPE_CHECKING, Any

from django import forms
from django.contrib.admin import helpers
from django.contrib.admin.utils import lookup_field, quote
from django.core.exceptions import ObjectDoesNotExist
Expand Down Expand Up @@ -239,3 +240,14 @@ class UnfoldAdminMultipleAutocompleteModelChoiceField(
AutocompleteFieldMixin, ModelMultipleChoiceField
):
widget = UnfoldAdminMultipleAutocompleteModelChoiceFieldWidget


class UnfoldAdminJSONSchemaField(forms.JSONField):
def __init__(self, schema: dict[str, Any], *args: Any, **kwargs: Any) -> None:
self.schema = schema
super().__init__(*args, **kwargs)

def widget_attrs(self, widget: Widget) -> dict[str, Any]:
attrs = super().widget_attrs(widget)
attrs.update({"schema": self.schema})
return attrs
5 changes: 5 additions & 0 deletions src/unfold/models/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from unfold.models.fields import JSONSchemaField

__all__ = [
"JSONSchemaField",
]
38 changes: 38 additions & 0 deletions src/unfold/models/fields.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from typing import Any

from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import Model

from unfold.fields import UnfoldAdminJSONSchemaField


class JSONSchemaField(models.JSONField):
def __init__(self, *args: Any, **kwargs: Any) -> None:
self.schema = kwargs.pop("schema", {})
super().__init__(*args, **kwargs)

def formfield(self, **kwargs: Any) -> UnfoldAdminJSONSchemaField:
defaults = {
"form_class": UnfoldAdminJSONSchemaField,
"schema": self.schema,
}
defaults.update(kwargs)
return super().formfield(**defaults)

def validate(self, value: Any, model_instance: Model | None) -> None:
super().validate(value, model_instance)

if not self.schema:
return

try:
import jsonschema
except ImportError:
return

try:
jsonschema.validate(value, self.schema)
except jsonschema.ValidationError as e:
paths = ", ".join(str(p) for p in e.path)
raise ValidationError(f"{paths}: {e.message}") from e
5 changes: 4 additions & 1 deletion src/unfold/overrides.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
from django.db import models

from unfold import widgets
from unfold.models import JSONSchemaField
from unfold.widgets import UnfoldAdminJSONSchemaWidget

FORMFIELD_OVERRIDES: dict[Any, Any] = {
models.DateTimeField: {
Expand All @@ -27,8 +29,9 @@
models.FloatField: {"widget": widgets.UnfoldAdminDecimalFieldWidget},
models.FileField: {"widget": widgets.UnfoldAdminFileFieldWidget},
models.ImageField: {"widget": widgets.UnfoldAdminImageFieldWidget},
models.JSONField: {"widget": widgets.UnfoldAdminTextareaWidget},
models.DurationField: {"widget": widgets.UnfoldAdminTextInputWidget},
models.JSONField: {"widget": widgets.UnfoldAdminTextareaWidget},
JSONSchemaField: {"widget": UnfoldAdminJSONSchemaWidget},
}

######################################################################
Expand Down
6 changes: 6 additions & 0 deletions src/unfold/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,12 @@
CHECKBOX_CLASSES,
FILE_CLASSES,
INPUT_CLASSES,
LABEL_CLASSES,
PROSE_CLASSES,
RADIO_CLASSES,
SELECT_CLASSES,
SWITCH_CLASSES,
TEXTAREA_CLASSES,
)

CONFIG_DEFAULTS = {
Expand All @@ -30,8 +33,11 @@
"LANGUAGE_FLAGS": {},
"FORMS": {
"classes": {
"label": " ".join(LABEL_CLASSES),
"prose": " ".join(PROSE_CLASSES),
"text_input": " ".join(INPUT_CLASSES),
"textarea": " ".join(TEXTAREA_CLASSES),
"select": " ".join(SELECT_CLASSES),
"checkbox": " ".join(CHECKBOX_CLASSES),
"button": " ".join(BUTTON_CLASSES),
"radio": " ".join(RADIO_CLASSES),
Expand Down
2 changes: 1 addition & 1 deletion src/unfold/static/unfold/css/styles.css

Large diffs are not rendered by default.

27 changes: 27 additions & 0 deletions src/unfold/static/unfold/js/app.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
window.addEventListener("load", (e) => {
initJSONSchemaEditor();

fileInputUpdatePath();

dateTimeShortcutsOverlay();
Expand All @@ -16,6 +18,31 @@ window.addEventListener("load", (e) => {
scrollSidebarNav();
});

/*************************************************************
* JSON Schema Editor
*************************************************************/
function initJSONSchemaEditor() {
document.querySelectorAll(".jsonschema-container").forEach((container) => {
const el = document.getElementById(container.dataset.targetId);

const instance = new Jedison.Create({
container: container,
theme: new ThemeUnfold(
JSON.parse(document.getElementById("formClasses").textContent),
),
schema: JSON.parse(
document.getElementById(container.dataset.schemaId).textContent,
),
});

instance.setValue(JSON.parse(el.value));

instance.on("change", () => {
el.value = JSON.stringify(instance.getValue());
});
});
}

/*************************************************************
* Switch theme
*************************************************************/
Expand Down
21 changes: 21 additions & 0 deletions src/unfold/static/unfold/js/jedison/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License Copyright (c) 2025 German Bisurgi

Permission is hereby granted, free
of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the
following conditions:

The above copyright notice and this permission notice
(including the next paragraph) shall be included in all copies or substantial
portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
1 change: 1 addition & 0 deletions src/unfold/static/unfold/js/jedison/jedison.js

Large diffs are not rendered by default.

118 changes: 118 additions & 0 deletions src/unfold/static/unfold/js/jedison/jedison.unfold.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
class ThemeUnfold extends Jedison.Theme {
constructor(formClasses = null) {
super();

this.formClasses = formClasses;
this.buttonClasses = [
"border",
"border-base-200",
"bg-primary-600",
"border-transparent",
"text-white",
"cursor-pointer",
"font-medium",
"inline-flex",
"group",
"items-center",
"gap-1",
"mt-3",
"px-3",
"py-2",
"relative",
"rounded-default",
"justify-center",
"whitespace-nowrap",
"hover:bg-primary-600/80",
];
}

getMultipleControl(config = {}) {
const multipleControl = super.getMultipleControl(config);
const { container } = multipleControl;

container.classList.add(
...["flex", "flex-col", "gap-3", "max-w-2xl", "w-full"],
);

return multipleControl;
}

getAddPropertyButton(config) {
const btn = super.getAddPropertyButton(config);
btn.classList.add(...this.buttonClasses, "w-full");
return btn;
}

getLabel(config) {
const labelObj = super.getLabel(config);
this.addCssClasses(labelObj.label, "label");

return labelObj;
}

getInputControl(config) {
const control = super.getInputControl(config);
const { input, container, messages, description } = control;
this.addCssClasses(input, "text_input");

container.classList.add(...["group", "relative"]);
container.appendChild(messages);
container.appendChild(description);
return control;
}

getSelectControl(config) {
const control = super.getSelectControl(config);
const { input, container, messages, description } = control;

this.addCssClasses(input, "select");

container.classList.add(...["group", "relative", "select-wrapper"]);
container.appendChild(messages);
container.appendChild(description);
return control;
}

getTextareaControl(config) {
const control = super.getTextareaControl(config);
const { input, container, messages, description } = control;

this.addCssClasses(input, "textarea");

container.classList.add(["group", "relative"]);
container.appendChild(messages);
container.appendChild(description);
return control;
}

getCheckboxControl(config) {
const control = super.getCheckboxControl(config);
const { container, formGroup, input, description, messages } = control;

formGroup.classList.add("flex", "items-center", "gap-2", "*:mb-0");

this.addCssClasses(input, "checkbox");

container.classList.add("group");
container.appendChild(messages);
container.appendChild(description);
return control;
}

getErrorFeedback(config) {
const html = document.createElement("div");

html.classList.add("jedi-error-message");
html.textContent = config.message;

return html;
}

addCssClasses(el, name) {
this.formClasses[name].split(/\s+/).forEach((cls) => {
if (cls) el.classList.add(cls);
});

return el;
}
}
Loading
Loading