Reputation: 35
I am looking for a way to switch and display a form in template, depending on choice in CharField in another form.
My app has the following models:
class Damage(models.Model):
damage_place = models.CharField()
damage_date = models.DateField()
class DamageType1(models.Model):
damage = models.ForeignKey(Damage)
...
class DamageType2(models.Model):
damage = models.ForeignKey(Damage)
...
class DamageType3(models.Model):
damage = models.ForeignKey(Damage)
...
Damage model has a DamageForm(forms.ModelForm) that is filled in by another user.
Each DamageType model has different fields (marked as ... for simplicity) and own DamageTypeForm1(forms.ModelForm), DamageTypeForm2(forms.ModelForm) and DamageTypeForm3(forms.ModelForm).
There is also a form in a template specifying which DamageType to choose:
class DamageSpecify(forms.Form):
DAMAGE_CHOICES = [
('DamageType1', 'DamageType1'),
('DamageType2', 'DamageType2'),
('DamageType3', 'DamageType3'),
]
damage_type = forms.CharField(choices=DAMAGE_CHOICES )
And now, after choose specific damage_type in DamageSpecify I would like to display the filled DamageForm and empty DamageType(1, 2 or 3) in template to fill and save both forms.
How could this be done?
Upvotes: 1
Views: 608
Reputation: 8202
How I'd tackle it. Write 4 forms. One, with a single ChoiceField. The other 3, to get the appropriate inputs for damage types 1 to 3 as chosen in the first. Display all the forms in your template:
<form> {% csrf_token %}
{{damage_type_form.as_p}}
<div id="type1">
{{damage_form_1.as_p}}
</div>
<div id="type2">
{{damage_form_2.as_p}}
</div>
<div id="type3">
{{damage_form_3.as_p}}
</div>
<input type="submit" ...>
</form>
(obviously, pass the four forms in your context, as you'd normally pass just one)
In your view POST processing, you will use the damage_type
to determine which form is to be validated and used. Bind all four forms (to request.POST), then use the choice to decide which one gets validated and used. Ignore the other two.
(This may be the first time I've actually thought that a Function-based view will probably be easier than using the Class-Based Views)
Finally, write some JS that will hide the <div>
s that are not selected in the damage_type pulldown/ ChoiceField.
Upvotes: 1