I'd like to create a form that includes fields from two separate models, along with some other regular (non-model) fields. The form will create an instance of each model. I don't think I can use inline formsets for this, since I don't want to include all the fields from both models.
I'd like to create the form field without hard-coding the type of the model fields.
I know I can get a form field from a model field using model_field.formfield()
. But how can I get the specific model field?
My first solution:
def get_fields(model_class):
fields = {}
for f in model_class._meta.fields:
fields[f.name] = f
class MyForm(forms.Form):
foo_name = get_fields(Foo)['name'].formfield()
bar_name = get_fields(Bar)['name'].formfield()
other_field = ...
Is there an equivalent of get_fields
already? Is this a bad idea? I'm uncomfortable relying on the model _meta
attribute. Or am I going about this the completely wrong way?