编辑:我最终彻底检查了我的代码以使用抽象继承,并且效果更好。我建议在尝试使用 Profiles 之前先探索一下。通过抽象继承,您可以更轻松地坚持使用 UpdateView/CreateView 之类的东西
吓坏了。如果您不需要将下拉列表作为模型的一部分,请使用 crimsonpython24 的答案。如果你这样做了,诀窍就是使用 onchange 下拉列表发回你的视图。
class AppleForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["color"].widget.attrs.update({"onchange": "this.form.submit()"})
class Meta:
...
现在,当用户选择他们想要的 Pawn(或 Apple)类型时,它会发布。
这是我的观点:
class AppleCreate(LoginRequiredMixin, View):
login_url = "/login/"
@staticmethod
def _create_apple(pawn_form, profile_form):
apple = apple_form.save()
profile_obj = profile_form.save(commit=False)
profile_obj.apple = apple
profile_obj.save()
return redirect(reverse("list_apples"))
def get(self, request):
context = {"apple_form": AppleForm()}
return render(request, "my/template.html", context=context)
def post(self, request):
apple_form = AppleForm(request.POST)
apple_color = request.POST.get("color", "")
profile_form_selector = {"Red": RedAppleProfileForm(request.POST), "Green": GreenAppleProfileForm(request.POST)}
profile_form = profile_form_selector.get(apple_color, "")
if apple_color and apple_form.is_valid() and profile_form.is_valid():
return AppleCreate._create_apple(apple_form, profile_form)
else:
return render(request, "my/template.html", context={"apple_form": pawn_form, "profile_form": profile_form})
基本上在你的 post 方法中,如果你有所有的数据,你就可以完成。如果不这样做,则需要重新呈现表单以及要显示的所有字段。