Django表单中多个字段的自定义验证

qlckcl4x  于 2023-03-13  发布在  Go
关注(0)|答案(4)|浏览(146)

我想在一个定制的clean方法中验证它的一些字段。
目前为止我有这个

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

但是,如果两个子句都无效,则只会显示其中一条消息。如何才能获得所有无效消息?而且,我无法获得特定于字段的消息-如何才能包括要为特定字段显示的消息?
任何帮助都很感激。

epfja78i

epfja78i1#

存储错误,直到方法结束才引发错误:

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
zsbz8rwp

zsbz8rwp2#

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

goqiplq2

goqiplq23#

发生这种情况是因为您使用的是raise。请尝试在代码中将其替换为以下两行:

del self.cleaned_data['piece']

以及

del self.cleaned_data['span']
j5fpnvbx

j5fpnvbx4#

这似乎在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 提供更多详细信息。

相关问题