def get_formset(self, request, view, obj=None, **kwargs): """Returns a BaseInlineFormSet class for use in admin add/change views.""" if self.declared_fieldsets: fields = flatten_fieldsets(self.declared_fieldsets) else: fields = None if self.exclude is None: exclude = [] else: exclude = list(self.exclude) exclude.extend(kwargs.get("exclude", [])) exclude.extend(self.get_readonly_fields(request, obj)) # if exclude is an empty list we use None, since that's the actual # default exclude = exclude or None defaults = { "form": self.get_form_class(request, obj), #TODO this needs meta "formset": self.formset, "fields": fields, "exclude": exclude, "formfield_callback": curry(self.formfield_for_field, request=request, view=view), #view=None "extra": self.extra, "max_num": self.max_num, "can_delete": self.can_delete, "schema": self.schema, } defaults.update(kwargs) return inlinedocumentformset_factory(self.model, self.dotpath, **defaults)
def test_inline_formset_factory(self): from dockit.forms.formsets import inlinedocumentformset_factory instance = ComplexObject(field1="field1") instance.save() formset = inlinedocumentformset_factory(ComplexObject, dotpath="addresses") form = formset(instance=instance) self.assertFalse(form.is_valid()) addr = { "street_1": "10533 Mesane Rd", "city": "San Diego", "postal_code": "92126", "country": "US", "region": "CA", } data = {"form-TOTAL_FORMS": 1, "form-INITIAL_FORMS": 0} # for i in range(1, 11): # data['form-%i-DELETE' % i] = 'checked' for key, value in addr.iteritems(): data["form-0-%s" % key] = value form = formset(instance=instance, data=data) self.assertTrue(form.is_valid(), str(form.errors)) form.save() self.assertEqual(len(instance.addresses), 1) data = {"form-TOTAL_FORMS": 2, "form-INITIAL_FORMS": 1, "form-0-DELETE": "checked"} for key, value in addr.iteritems(): data["form-1-%s" % key] = value form = formset(instance=instance, data=data) self.assertTrue(form.is_valid(), str(form.errors)) form.save() self.assertEqual(len(instance.addresses), 1)