17 ms·
An alternative to this is to use a Form. You can have a model that produces the form configuration (relations for each field in the form for example) and produc
by orf 8y ago
An alternative to this is to use a Form. You can have a model that produces the form configuration (relations for each field in the form for example) and produce this Form on request.
Then, when the form is saved, take the resulting dictionary and save it to a JSONField in a 'result' model. If you want to re-display the form with the results, just create the form from the configuration model and add the data from the result model.
I've had great results with this technique, and you can model any field except a foreign key. Django forms provides the validation, and the backing storage is dynamic so you can change fields easily. It seems less fragile than creating models like this article proposes.
- shezi 8y agoThat's about what the author says right at the top of the article. However, this is only more flexible in the front end. If you want to do anything with your data in the back end, a JSONField will help you less than fully structured data. While you can do some queries on JSON fields, most of the richer queries will have to be done in python, slowing processing down. If you're looking for runtime-changeable, structured data that you can run complex queries on, ModelModels sound like a good alternative. Most enterprise applications are in this area.
- spapas82 8y agoI'd written a blog post describing more or less this 5 years ago: https://spapas.github.io/2013/12/24/django-dynamic-forms/ https://spapas.github.io/2013/12/24/django-dynamic-forms/
- shimon 8y agoI did something like this in an app for art collectors once. My client wanted very different forms and styles for different objects -- say a coin vs. a stamp. The templates to render the forms were thus very complex and specified every field in the form, so rather than define fields in both the Form class and the template, I made a dynamic Form-subclass generator that would read the template file and create the class to process and store it. Typing that out now, I'm both enjoying the cleverness of that solution and wondering if it was at all justifiable. It probably would have made a good blog post.
- deleted 8y ago[deleted]