6

我想在自定义清理方法中验证多个字段。

到目前为止我有这个:

class ProjectInfoForm(forms.Form):
    module = forms.ModelChoiceField(
        queryset=Module.objects.all(),
    )
    piece = forms.CharField(
        widget=forms.Select(),
        required=False,
    )
    span = forms.IntegerField(
        max_value=100,
        initial=48
    )
    max_span = forms.IntegerField(
        max_value=100,
        initial=0
    )


    def clean(self):
        span = self.cleaned_data['span']
        max_span = self.cleaned_data['max_span']
        piece = self.cleaned_data.['piece']

        # validate piece 
        try:
            Piece.objects.get(pk=m)
        except Piece.DoesNotExist:
            raise forms.ValidationError(
                'Illegal Piece selected!'
            )
            self._errors["piece"] = "Please enter a valid model"

        # validate spans
        if span > max_span:
            raise forms.ValidationError(
                'Span must be less than or equal to Maximum Span'
            )
            self._errors["span"] = "Please enter a valid span"
        return self.cleaned_data

但是,如果两个子句都无效,这只会给我一条消息。如何获取所有无效消息。此外,我没有收到特定于字段的消息 - 如何包含要为特定字段显示的消息?

非常感谢任何帮助。

4

4 回答 4

6

存储错误并且在方法结束之前不要引发它们:

def clean(self):
    span = self.cleaned_data['span']
    max_span = self.cleaned_data['max_span']
    piece = self.cleaned_data.['piece']
    error_messages = []

    # validate piece 
    try:
        Piece.objects.get(pk=m)
    except Piece.DoesNotExist:
        error_messages.append('Illegal Piece selected')
        self._errors["piece"] = "Please enter a valid model"

    # validate spans
    if span > max_span:
        error_messages.append('Span must be less than or equal to Maximum Span')
        self._errors["span"] = "Please enter a valid span"

    if len(error_messages):
        raise forms.ValidationError(' & '.join(error_messages))

    return self.cleaned_data
于 2012-12-12T18:05:33.213 回答
1

在这种情况下,您应该编写自定义clean_FIELDNAME方法。这样,以后在模板中使用 {{form.errors}} 时,可以显示以字段为中心的验证错误。clean方法用于验证跨越多个字段的逻辑。看看我在上面发布的链接,你需要知道的关于验证 django 表单的一切都在那里。

于 2012-12-12T18:01:02.100 回答
0

发生这种情况是因为您正在使用raise. 尝试用代码中的这两行替换它:

del self.cleaned_data['piece']

del self.cleaned_data['span']
于 2012-12-12T18:07:27.447 回答
0

看来这在 Django 的更高版本中发生了变化(这似乎在 2.1 及更高版本中工作):


from django import forms

class ContactForm(forms.Form):
    # Everything as before.
    ...

    def clean(self):
        cleaned_data = super().clean()
        cc_myself = cleaned_data.get("cc_myself")
        subject = cleaned_data.get("subject")

        if cc_myself and subject and "help" not in subject:
            msg = "Must put 'help' in subject when cc'ing yourself."
            self.add_error('cc_myself', msg)
            self.add_error('subject', msg)

https://docs.djangoproject.com/en/dev/ref/forms/validation/#raising-multiple-errors有更多细节。

于 2019-08-14T19:24:09.303 回答