20👍
✅
Yes, it’s possible to create forms dynamically in Django. You can even mix and match dynamic fields with normal fields.
class EligibilityForm(forms.Form):
def __init__(self, *args, **kwargs):
super(EligibilityForm, self).__init__(*args, **kwargs)
# dynamic fields here ...
self.fields['plan_id'] = CharField()
# normal fields here ...
date_requested = DateField()
For a better elaboration of this technique, see James Bennett’s article: So you want a dynamic form?
7👍
If you run
python manage.py shell
and type:
from app.forms import PictureForm
p = PictureForm()
p.fields
type(p.fields)
you’ll see that p.fields is a SortedDict. you just have to insert a new field. Something like
p.fields.insert(len(p.fields)-2, 'fieldname', Field())
In this case it would insert before the last field, a new field. You should now adapt to your code.
Other alternative is to make a for/while loop in your template and do the form in HTML, but django forms rock for some reason, right?
- [Django]-Running Django with FastCGI or with mod_python
- [Django]-Preventing django from appending "_id" to a foreign key field
- [Django]-Create if doesn't exist
7👍
Use either multiple forms (django.forms.Form not the tag)
class Foo(forms.Form):
field = forms.Charfield()
forms = [Foo(prefix=i) for i in xrange(x)]
or add multiple fields to the form dynamically using self.fields.
class Bar(forms.Form):
def __init__(self, fields, *args, **kwargs):
super(Bar, self).__init__(*args, **kwargs)
for i in xrange(fields):
self.fields['my_field_%i' % i] = forms.Charfield()
- [Django]-Difference between @cached_property and @lru_cache decorator
- [Django]-How to query abstract-class-based objects in Django?
- [Django]-Django: Redirect logged in users from login page
Source:stackexchange.com