all,
I'd like to find a way to combine two model forms (ie., modelForm
subclasses).
I understand that there's no way I can do this so that the resulting
form is somehow bound to both models at the same time - all i need is
that the resulting HTML form contains input fields corresponding to all
of the fields of the two models together.
At the moment my half-assed solution looks something like this;
class modelOne(models.Model):
# various fields
...
class modelTwo(models.Model)::
fld1 = models.someFieldType
fld2 = models.someFieldType
...
class OneTwoForm(forms.ModelForm):
fld1 = forms.someFieldType # corresponds to modelTwo.fld1
fld2 = forms.someFieldType # corresponds to modelTwo.fld2
class Meta:
model = modelOne #based on modelOne only
ie. I create a modelForm class based on modelOne, then manually add the
fields corresponding to the modelTwo model
Can I do this more neatly without having to manually specify the
additional fields manually by somehow combining two modelForms?
MBOI
----
I get around the problem of not being able to initialise the
classOneForm with a classTwo instance by adding the following method to
the form;
def update_instances(self, *instances, **kwargs):
commit = kwargs['commit'] if 'commit' in kwargs.keys() else True
for inst in instances:
for f in inst._meta.fields:
if f.attname in self.fields:
setattr(inst,f.attname,self.cleaned_data[f.attname])
if commit:
try: inst.save()
except: raise Exception('%s: Could not save item' % str(inst))
return instances
which means that I can do things like this;
c1 = modelOne()
c2 = modelTwo()
# populate the form with POSTed data
f = OneTwoForm(request.POST.copy())
# apply that data to the two model instances
OneTwoForm.update_instances(c1,c2)
note that all this assumes that the field names are unique to the two
objects. eg. if both modelOne and modelTwo has fields 'info', then this
approach wouldn't work, as the same HTML form field value would be
applied to both instances.
--
[][][] Andy Wilson | mob: +44 (0)7739 908 253
[][] Managing Director | tel: +44 (0)20 7729 7060
[] [] LShift Ltd | web: www.lshift.net
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---