Forms, Getting Your Money's Worth
View more presentations from kingkilr.
And the first examples code follows:
from django.forms.util import ErrorList
from django.utils.datastructures import SortedDict
def multiple_form_factory(form_classes, form_order=None):
if form_order:
form_classes = SortedDict([(prefix, form_classes[prefix]) for prefix in
form_order])
else:
form_classes = SortedDict(form_classes)
return type('MultipleForm', (MultipleFormBase,), {'form_classes': form_classes})
class MultipleFormBase(object):
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None, error_class=ErrorList, label_suffix=':',
empty_permitted=False):
if prefix is None:
prefix = ''
self.forms = [form_class(data, files, auto_id, prefix + form_prefix,
initial[i], error_class, label_suffix, empty_permitted) for
i, (form_prefix, form_class) in enumerate(self.form_classes.iteritems())]
def __unicode__(self):
return self.as_table()
def __iter__(self):
for form in self.forms:
for field in form:
yield field
def is_valid(self):
return all(form.is_valid() for form in self.forms)
def as_table(self):
return '\n'.join(form.as_table() for form in self.forms)
def as_ul(self):
return '\n'.join(form.as_ul() for form in self.forms)
def as_p(self):
return '\n'.join(form.as_p() for form in self.forms)
def is_multipart(self):
return any(form.is_multipart() for form in self.forms)
def save(self, commit=True):
return tuple(form.save(commit) for form in self.forms)
save.alters_data = True
EuroDjangoCon has been a blast thus far and after the conference I'll do a blogpost that does it justice.
So how would this work with foreign key dependencies? Lets say you are filling out a contact form which contains a contact model with foreign keys for the user model and the location model.
ReplyDeleteHi Alex,
ReplyDeletethanks for sharing this - I think, it's a pretty interesting idea.
However, when I use the code displayed above(which is different from the slides code), I experience some problems.
First thing I noticed:
'... i, form_prefix, form_class in enumerate(self.form_classes)...' in __init__.
I get a ValueError saying 'need more than 2 values to unpack'.
After working around this, I got stuck with several other things(probably caused by my workarounds :)
Could you maybe have a look into this?
Thanks again!
carsten