Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing dynamic fields in Django forms

Django's form library has a feature of form sets that allow you to process dynamically added forms. For example you would use form sets if your application has a list of bookmarks you could use form sets to process multiple forms that each represent a bookmark.

What about if you want to dynamically add a field to a form? An example would be a survey creation page where you can dynamically add an unlimited number of questions. How do you handle this in Django?

like image 584
hekevintran Avatar asked Mar 24 '10 08:03

hekevintran


People also ask

How to add dynamic fields in form in Django?

To dynamically add field to a form with Python Django, we can add the form with a for loop. to create the MyForm form that has a for loop in the __init__ method that creates CharField s and add them into the self. fields dictionary dynamically. We set the extra argument to a list we get from request.

Can we create dynamic models in Django?

The flexibility of Python and Django allow developers to dynamically create models to store and access data using Django's ORM.

What is formset in Django?

A formset is a layer of abstraction to work with multiple forms on the same page. It can be best compared to a data grid. Let's say you have the following form: >>> from django import forms >>> class ArticleForm(forms.


1 Answers

Look at this recent post by Jacob Kaplan-Moss, one of the original founders of Django: "Dynamic form generation". It uses an example to show you the process step by step. Great read.

There is also a 2008 article by James Bennett, Django's release manager.

like image 130
Ludwik Trammer Avatar answered Oct 13 '22 12:10

Ludwik Trammer