Django 内联表单集不保存默认值

Django inline formset not saving default values

我有一个 child 内联表单集,如果它已被用户更改,它会保存,但如果保持不变,则不会保存默认值。

SeVsEff 是 child,patient 是 parent

models.py

class Patient(TimeStampedModel):
    patient_id = models.UUIDField(
        primary_key=True, unique=True, default=uuid.uuid4, editable=False
    )
    name = models.CharField("Patient Name", max_length=255)

    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL
    )

class SeVsEff(TimeStampedModel):
    value = models.IntegerField(default=20)
    patient = models.ForeignKey(Patient, on_delete=models.CASCADE)

forms.py

class PatientForm(ModelForm):
    class Meta:
        model = Patient
        fields = ["name"]

SevseffFormSet = inlineformset_factory(
    Patient,
    SeVsEff,
    fields=("value",),
    widgets={'value': RangeInput()},
    extra=0,
    min_num=1,
    validate_min=True,
    labels=None,
)

views.py

    def post(self, *args, **kwargs):
        form = PatientForm(data=self.request.POST)
        sevseff_formset = SevseffFormSet(data=self.request.POST)

        if form.is_valid():
            patient_instance = form.save()
            patient_instance.user = self.request.user
            patient_instance.save()

            if sevseff_formset.is_valid():
                sevseff_name = sevseff_formset.save(commit=False)
                for sevseff in sevseff_name:
                    sevseff.patient = patient_instance
                    sevseff.save()

所以我认为问题在于 sevseff_formset 未注册为有效,除非它被更改,但如果我添加类似:

            if not sevseff_formset.has_changed():
                sevseff_name = sevseff_formset.save(commit=False)
                for sevseff in sevseff_name:
                    sevseff.patient = patient_instance
                    sevseff.save()

这不起作用,因为 sevseff_name 是空的。

这样做:

sevseff_name = sevseff_formset.save(commit=False)
for sevseff in sevseff_name:
    sevseff.patient = patient_instance
    sevseff.save()
if not sevseff_name:
    SeVsEff(value=20, patient=patient_instance).save()

来自https://forum.djangoproject.com/t/django-inline-formset-not-saving-default-values/10647/3

的解决方案