Multiple different forms in a view Django
I was wondering if there was a way to have multiple different forms in a single view and to press a single submit button for the information to be stored. I have the following forms, the first one is my general form that should be created first:
class GeneralForm(forms.ModelForm):
name = forms.CharField(max_length=50)
TYPE_CHOICES = (
("C","C"),
("E","E")
)
STATUS_CHOICES = (
("A", "A"),
("F", "F"),
)
type=forms.ChoiceField(choices=STATUS_CHOICES)
number=forms.CharField(max_length=50)
TURN_CHOICES = (
("1", "1"),
("2", "2"),
("3", "3")
)
turn = forms.ChoiceField(choices=TURN_CHOICES)
class Meta:
model = models.General
fields=["name","type","number","turn"]
The second one needs an instance of the first one and so does the third:
class TypeOneForm(forms.ModelForm):
num_chairs=forms.IntegerField()
num_instalations = forms.IntegerField()
total = forms.IntegerField()
num_programs = forms.IntegerField()
class Meta:
model = models.TypeOne
fields=["num_chairs","num_instalations","total","billetes_cien"]
class TypeTwoForm(forms.ModelForm):
num_available_seats=forms.IntegerField()
num_available_instalations = forms.IntegerField()
total = forms.IntegerField()
num_new_programs = forms.IntegerField()
class Meta:
model = models.TypeTwo
fields=["num_available_seats", "num_available_instalations","total","num_programs" ]
I was reading I could use FormSets but im not sure if i can use different forms instead of multiple instances of the same form
You can use get_context_data()
for that and put a form in a context, But if you want to fill some fields of the form you need to validate the form.
def get_context_data(self, **kwargs):
context = super().get_context_data()
context['general_form'] = GeneralForm()
return context
Validating like that
def post(self, request, *args, **kwargs):
form = GeneralForm(request.POST)
if form.is_valid():
form.instance.author = request.user
form.save()
return redirect(reverse('general_form'))