[Answer]-Define crispy forms context names for two forms in one

1👍

view:

 class BusinessView(...):
 ...

 def get_context_data(self, **kwargs):
      context = super(BusinessView, self).get_context_data(**kwargs)
      context['form_2'] = AttractionExtrasForm(instance=self.model())  # if createview
      # context['form_2'] = AttractionExtrasForm(instance=self.object)  # if updateview     

      return context

And you have to validate both separately

if form.is_valid() and form_2.is_valid():
    return self.form_valid(form, form_2)
else:
    return self.form_invalid(form, form_2)

If you models is connected (one have FK field to another)

def form_valid(self, form, form_2):
    if not self.object:  # createview
        self.object = form.save()
    else:  # updateview
        form.save()

    form_2.instance = self.object
    form_2.save()

    return HttpResponseRedirect(self.get_success_url())

def form_invalid(self, form, form_2):
    return self.render_to_response(
        self.get_context_data(
            form=form,
            form_2=form_2
        )
    )

And if you want many instances of form_2 can use inlineformset_factory https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#django.forms.models.BaseInlineFormSet

template:

<form method="post">{% csrf_token %}
    {% crispy form %}
    {% crispy form_2 %}
</form>

Leave a comment