Dynamic Forms
Recently I have been doing work with form fields populated from the database. Obviously this, as standard, is not supported by Django.
After quite some time search, and 3 different approaches to this I decided to make my own. It has not been fully tested yet, but once it has I will post the code.
I havn’t released this class yet so don’t go trying it
To give you an idea as to the usage, note dfm
is (currently) a 12 line class for convenience only, you could easily work without it.
for f in FormOption.objects.all():
dfm.add_field(
f.field_name,
forms.BooleanField(required=False, label=f.title)
)
TheForm = dfm.form(_TheForm)
if request.method == 'POST':
form = TheForm(request.POST)
else:
form = TheForm()
As you can see, after the first few lines, you go back to your normal Django code. It works with only a few dynamic fields, as well as displays the fields in the order you defined them. That was the main problem at least one of the alternatives I found.
You are also able to create your clean
function in the forms to do some basic validation.
Expect this in a few weeks after some more testing has been done.