好的,所以我有一个带有几个inlineformset_factory添加的通用CreateView。与此处的示例类似: Django class-based CreateView and UpdateView with multiple inline formsets
一个是使用父模型按预期生成一个新记录,但是第二个只包含布尔字段的记录不是。我没有为内联formset生成我自己的模型表单,而是使用默认值。一旦我将一个charfield字段添加到违规模型中,保存工作,我可以看到新记录,在该内联formset(和模型)中只有布尔字段,我什么也没有记录,也没有错误。
编辑代码示例>
#models.py
class Mentor(models.Model):
title = models.CharField(max_length=15, choices=SALUTATION_CHOICES, blank=True, null=True)
first_name = models.CharField(blank=False, null=False, max_length=80)
last_name = models.CharField(blank=False, null=False, max_length=80)
class MentorSetting(models.Model):
mentor = models.OneToOneField('Mentor')
mentor_status = models.BooleanField(default=True)
question_status = models.BooleanField(default=True)
#forms.py
class MentorForm(ModelForm):
class Meta:
model = Mentor
fields = ['title','first_name','last_name',]
SettingsFormSet = inlineformset_factory(Mentor, MentorSetting,
fields=('mentor_status','question_status',),
extra=1,
can_delete=True)
#views.py
class MentorCreateView(CreateView):
template_name = 'mentor/mentor_form.html'
model = Mentor
form_class = MentorForm
def get(self, request, *args, **kwargs):
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
settings_form = SettingsFormSet()
return self.render_to_response(
self.get_context_data(form=form,
settings_form=settings_form))
def post(self, request, *args, **kwargs):
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
settings_form = SettingsFormSet(self.request.POST)
if (form.is_valid() and settings_form.is_valid()):
return self.form_valid(form, settings_form)
else:
return self.form_invalid(form, settings_form)
def form_valid(self, form, settings_form):
self.object = form.save()
settings_form.instance = self.object
settings_form.save()
return HttpResponseRedirect(self.get_success_url())
def form_valid(self, form, settings_form):
return self.render_to_response(
self.get_context_data(form=form,
settings_form=settings_form))
如果有人能解释为什么会很棒。
马修