Pieces of JSON Schema are easily used with frontend JavaScript libraries like Angular, React and Alpaca to create an html form with validation. This should also work with a Python solution django-jsonschema-form or django-schemulator but I am new to Django and having a lot of trouble working it out..
Here is a screenshot from the video from AlpacaJS which communicates easily what this is supposed to achieve:
I have done some testing with the two libraries above, and the former seems much better maintained and less buggy, the only one of the two in PyPI.
My directory tree created by Django 1.11.4 looks like this:
.
├── db.sqlite3
├── jschemaforms
│ ├── admin.py
│ ├── apps.py
│ ├── forms.py
│ ├── __init__.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── manage.py
├── myproject
│ ├── __init__.py
│ ├── settings.py
│ ├── templates
│ │ ├── base.html
│ │ └── includes
│ ├── urls.py
│ └── wsgi.py
└── README.md
The docs for django-jsonschema-form specify a class:
# Overriding widgets for all instances of JSONField on PageAdmin form
class PageAdmin(admin.ModelAdmin):
formfield_overrides = {
JSONField: {'widget': JSONSchemaWidget(schema)}
}
Whereabouts in the directory tree is such a class supposed to go?
schema
is the piece of json you feed it to define your form
I had a look at the various answers in this SO question to try to work it out:
Django Admin - Overriding the widget of a custom form field
It seems that forms.py and the ModelAdmin object are enough to implement this, but am not sure where in the tree the ModelAdmin object is supposed to live.
How can this be achieved with Django?
- rendering the form from jsonschema
- validating on client side what the user puts into the form against the jsonschema
- retrieving the data from the form POST request when the user clicks 'submit' as json
I am not sure if those two libraries are the answer..
The PageAdmin
class goes in a file called admin.py, next to its corresponding model.py. Here are the Django 1.11 docs on discovering admin files.
You also have to register the admin for your model. You use the django.contrib.admin.register
decorator for this. The same page has the docs for this decorator as well.
The usage goes something like
from somewhere import Page
from django.contrib import admin
# Overriding widgets for all instances of JSONField on PageAdmin form
@admin.register(Page)
class PageAdmin(admin.ModelAdmin):
formfield_overrides = {
JSONField: {'widget': JSONSchemaWidget(schema)}
}
This code snippet registers your PageAdmin
class as the ModelAdmin
for your Page
model.
来源:https://stackoverflow.com/questions/52990430/render-jsonschema-as-a-form-with-django-jsonschema-form-or-django-schemulator