如何在删除其中一个对象时验证模型表单的django formset

时间:2018-06-07 22:04:17

标签: django formset django-validation

我有一个Django formset来记录参加活动:

AttendanceFormSet = modelformset_factory(Registration,
                                          form=AttendanceForm,
                                          extra=0)

从此表单创建:

class AttendanceForm(forms.ModelForm):
    class Meta:
        model = Registration
        fields = (
            "absent",
            "late",
        )

来自这个模型:

class Registration(models.Model):
    event = models.ForeignKey(Event)
    student = models.ForeignKey(User, on_delete=models.CASCADE)
    # ...
    absent = models.BooleanField(default=False)
    late = models.BooleanField(default=False)

但是,有时参与者会在已加载考勤表后删除该事件。我希望能够优雅地处理这些情况。

在表单验证期间,如何判断注册对象是否不再存在?

我已尝试单独验证表单,但验证错误似乎没有用处:

if request.method =="POST":
    formset1 = AttendanceFormSet(
        request.POST, request.FILES,
        queryset=queryset,
    )

    for form in formset1.forms:
        if form.is_valid():
            form.save()
        else:
            print("form errors: " + str(form.errors))

发生这种情况时产生的错误如下所示:

form errors: <ul class="errorlist"><li>id<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li></ul>

0 个答案:

没有答案