How to get Django form field from model field?
Another solution can be to create one 'uber'-form that aggregates the concrete modelforms. The form supports the methods that a form normally provides and it forward them to all the child forms. Some will be simple, other complicated. The big advantage of that approach is that no code beyond the form is affected (client validation code and alike). The concept isn't really revolutionary but i guess complicated to add afterwards. Paul
There is now a documented API for getting the model field from a model class:
my_model_field = MyModel._meta.get_field('my_model_field_name')
Although it's not officially documented until Django 1.8, this should work with earlier Django versions too.
Once you have this, you can get the form field like so:
form_field = my_model_field.formfield()
You should never have to build the fields yourself unless you want some special behavior.
This should be as simple as using two ModelForm
s and an extra Form
inside one <form>
tag in your template with one submit button.
in forms.py:
class Model1Form(forms.ModelForm):
class Meta:
model = Model1
fields = ('fields', 'you', 'want')
class Model2Form(forms.ModelForm):
class Meta:
model = Model2
fields = ('fields', 'you', 'want')
class ExtraFieldsForm(forms.Form):
extra_field = form.TextField() # or whatever field you're looking for
in views.py:
form1 = Model1Form(request.POST or None)
form2 = Model2Form(request.POST or None)
form3 = ExtraFieldsForm(request.POST or None)
if form1.is_valid() and form2.is_valid() and form3.is_valid():
form1.save()
form2.save()
form3.save()
...do other stuff like a redirect...
and in the template:
<form method="POST" action="">{% csrf_token %}
<fieldset>
{{ form1|as_uni_form }}
{{ form2|as_uni_form }}
{{ form3|as_uni_form }}
<div class="form_block">
<input type="submit" value="Save both models"/>
</div>
</fieldset>
</form>
I'm used to using django-uni-form, but you can render the form fields however you like. Good luck with your site.
You also can take a look at django.forms.models.fields_for_model
.
That should give you a dictionary of fields, and then you can add the fields of the form