I'm creating a Django site and I would like to add dynamically generated forms based on JSON description which will come from an external source.
E.g. something like this:
[
{
"name": "first_name",
"label": "First Name",
"type": "char",
"max_length": 30,
"required": 1
},
{
"name": "last_name",
"label": "Last Name",
"type": "char",
"max_length": 30,
"required": 1
},
]
Would then give me a simple Django form with two CharFields which I would display to a user and save the values he/she puts in for further processing.
I searched but didn't find any app creating Django forms from JSON like this. I can write such app myself, I just wanted to know if there is anything already.
If not, do you at least know about any JSON schema format that would allow to describe forms? Again, I can come up with it myself but I wanted to have a look at some examples so I don't omit important possibilities and have something solid to start with.
Thanks!
You can use django-jsonforms like this:
forms.py:
from django.forms import ModelForm, Form
from django_jsonforms.forms import JSONSchemaField
first_name_schema = {
"type": "object",
"required": ["First Name"],
"properties": {
"First Name": {
"type": "string",
"maxLength": 30
}
}
}
last_name_schema = {
"type": "object",
"required": ["Last Name"],
"properties": {
"Last Name": {
"type": "string",
"maxLength": 30,
}
}
}
options = {"no_additional_properties": True}
class CustomForm(Form):
first_name = JSONSchemaField(schema = first_name_schema, options = options)
last_name = JSONSchemaField(schema = last_name_schema, options = options)
views.py:
from .forms import CustomForm
def some_view(request):
return render(request, 'some_html.html', {'form': CustomForm()})
some_html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="some_form" action="/path/to/some_view/" method="post">
{% csrf_token %}
{{ form.media }}
{{ form }}
<button type="submit">submit</button>
</form>
for more information visit docs
Edit:
You can remove the extra buttons in your form by modifying your option dictionary like this:
options = {
"no_additional_properties": True,
"disable_collapse": True,
"disable_edit_json": True,
"disable_properties": True
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With