无法使用django Form.clean()方法

py49o6xq  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(124)

我试图在一个表单中添加一些额外的验证,覆盖它的clean方法,但错误并没有引发,一个ValueError异常说“The view apps.orders.views.view didn't return an HttpResponse object.但是如果我在if条件中使用else子句来检查表单是否有效并打印form.errors,它会打印clean方法中创建的错误。为了记录,我使用的是表单沿着表单集。先谢了。
下面是表格:

class OrderForm(forms.ModelForm):
    """ModelForm Class for Orders objects."""
    class Meta:
        model = Order
        fields = '__all__'
        widgets = {
            'executor_signature_date': forms.DateInput(
                format=('%Y-%m-%d'),
                ),
            'customer_signature_date': forms.DateInput(
                format=('%Y-%m-%d'),
                ),
        }
    
    def clean(self):
        cleaned_data = super().clean()
        check_diagnosis = cleaned_data.get("check_diagnosis")
        repair = cleaned_data.get("repair")
        install = cleaned_data.get("install")
        maintenance = cleaned_data.get("maintenance")

        if (not check_diagnosis) and (not repair) and (not install) and (not maintenance):
            self.add_error(None, "At least one modality option must be checked.")
        else:
            return cleaned_data

字符串
check_diagnostic、repair、install和maintenance字段是布尔字段。
这里的观点:

def post(self, request, **kwargs):
    order = Order.objects.get(pk=kwargs['pk'])
    form = self.form_class(request.POST, instance=order)
    ItemTimesFormSet = modelformset_factory(ItemTimes, exclude=['order'])
    formset = ItemTimesFormSet(request.POST)

    if form.is_valid() and formset.is_valid():
        order.items.clear()
        form.save()
        for form in formset:
            if form.cleaned_data.get('item'):
                item = form.cleaned_data.get('item')
                times = form.cleaned_data.get('times')
                ItemTimes.objects.create(
                    order=order,
                    item=item,
                    times=times
                )

        return redirect(self.success_url)

bxfogqkk

bxfogqkk1#

当表单无效时,您不会返回任何特定的错误,只需像这样更新视图以处理表单中的错误:

def post(self, request, **kwargs):
    order = Order.objects.get(pk=kwargs['pk'])
    form = self.form_class(request.POST, instance=order)
    ItemTimesFormSet = modelformset_factory(ItemTimes, exclude=['order'])
    formset = ItemTimesFormSet(request.POST)

    if form.is_valid() and formset.is_valid():
        order.items.clear()
        form.save()
        for form in formset:
            if form.cleaned_data.get('item'):
                item = form.cleaned_data.get('item')
                times = form.cleaned_data.get('times')
                ItemTimes.objects.create(
                    order=order,
                    item=item,
                    times=times
                )

        return redirect(self.success_url)
    else:
        # Form is not valid, handle the error
        print(form.errors)  # Optional: Print the form errors for debugging

        # Provide an appropriate response, such as rendering the form again with the errors
        context = {
            'form': form,
            'formset': formset,
        }
        return self.render_to_response(context)

字符串
最好是在表单中添加错误,像这样:

from django.core.exceptions import ValidationError

def clean(self):
    cleaned_data = super().clean()
    check_diagnosis = cleaned_data.get("check_diagnosis")
    repair = cleaned_data.get("repair")
    install = cleaned_data.get("install")
    maintenance = cleaned_data.get("maintenance")

    if (not check_diagnosis) and (not repair) and (not install) and (not maintenance):
        raise ValidationError("At least one modality option must be checked.")

    return cleaned_data

相关问题