erikbwork, and I had a problem that you can include only one model in the general cool approach. I found a similar approach to it, like Miao, but more modular.
I wrote Mixin so you can use all the general representations of the class. Define the model, fields and now also child_model and child_field - and then you can wrap the fields of both models in a tag, as described by Zach.
class ChildModelFormMixin: ''' extends ModelFormMixin with the ability to include ChildModelForm ''' child_model = "" child_fields = () child_form_class = None def get_child_model(self): return self.child_model def get_child_fields(self): return self.child_fields def get_child_form(self): if not self.child_form_class: self.child_form_class = model_forms.modelform_factory(self.get_child_model(), fields=self.get_child_fields()) return self.child_form_class(**self.get_form_kwargs()) def get_context_data(self, **kwargs): if 'child_form' not in kwargs: kwargs['child_form'] = self.get_child_form() return super().get_context_data(**kwargs) def post(self, request, *args, **kwargs): form = self.get_form() child_form = self.get_child_form()
Usage example:
class ConsumerRegistrationUpdateView(UpdateView): model = Registration fields = ('firstname', 'lastname',) child_model = ConsumerProfile child_fields = ('payment_token', 'cart',)
Or with ModelFormClass:
class ConsumerRegistrationUpdateView(UpdateView): model = Registration fields = ('firstname', 'lastname',) child_model = ConsumerProfile child_form_class = ConsumerProfileForm
Done. Hope that helps someone.
LGG Jan 09 '17 at 23:57 2017-01-09 23:57
source share