我和erikbwork都有一个问题,即一个模型只能包含在一个通用的基于类的视图中。我找到了类似苗的类似方法,但是更加模块化。
我写了一个Mixin,因此您可以使用所有通用的基于类的视图。定义模型,字段,现在还定义child_model和child_field-然后可以将两个模型的字段包装在标签中,如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()
# check if both forms are valid
form_valid = form.is_valid()
child_form_valid = child_form.is_valid()
if form_valid and child_form_valid:
return self.form_valid(form, child_form)
else:
return self.form_invalid(form)
def form_valid(self, form, child_form):
self.object = form.save()
save_child_form = child_form.save(commit=False)
save_child_form.course_key = self.object
save_child_form.save()
return HttpResponseRedirect(self.get_success_url())
用法示例:
class ConsumerRegistrationUpdateView(UpdateView):
model = Registration
fields = ('firstname', 'lastname',)
child_model = ConsumerProfile
child_fields = ('payment_token', 'cart',)
或使用ModelFormClass:
class ConsumerRegistrationUpdateView(UpdateView):
model = Registration
fields = ('firstname', 'lastname',)
child_model = ConsumerProfile
child_form_class = ConsumerProfileForm
做完了 希望能对某人有所帮助。