我第一次使用Django inlineformsets,而我正试图处理我的观点。我已经能够创建我的创建和更新视图,但我对如何进行详细信息视图感到迷茫。我基本上有2个模型 - SchoolMain和SchoolSub与SchoolSub与SchoolMain建立了fk关系。 SchoolSub是我的表格。我的创建视图位于 -
之下class SchoolSubCreate(LoginRequiredMixin,UserPassesTestMixin,generic.CreateView):
model = SchoolMain
fields = '__all__'
def get_context_data(self, **kwargs):
data = super(SchoolSubCreate, self).get_context_data(**kwargs)
if self.request.POST:
data['schoolsub'] = SchoolSubFormSet(self.request.POST)
else:
data['schoolsub'] = SchoolSubFormSet()
def form_valid(self, form):
context = self.get_context_data()
schoolsub = context['schoolsub']
with transaction.atomic():
form.instance.user = self.request.user
self.object = form.save()
if schoolsub.is_valid():
schoolsub.instance = self.object
schoolsub.save()
return super(SchoolSubCreate, self).form_valid(form)
我理解如何创建一般的DetailView,但这只能获取我的主要模型的对象,即SchoolMain模型。但是我无法访问formset中的对象。非常感谢任何帮助。感谢。