以与错误消息相同的样式显示验证错误

问题描述 投票:0回答:1

我使用的是脆皮表格,使表格看起来不错,并添加了以下验证:

if age < 14:
            raise forms.ValidationError('Sorry, you must be atleast 14 years old to study with IPC IELTS')
        elif age > 110:
            raise forms.ValidationError('You entered a date of birth outside of the accepted range. Please try again')

        return data

[我的问题是,此错误消息以Flash消息形式显示在页面顶部,而其他消息(我未设置但却内置了脆性消息,例如当用户将必填字段留空时)显示为错误相关字段下的弹出消息框。

为了保持一致性,我不知道如何使添加的验证错误与其他内置的酥脆错误消息相同。

谢谢。

django django-crispy-forms
1个回答
0
投票

如果您要覆盖干净方法,则可以使用add_error()

def clean(self):
    data = self.cleaned_data
    age = data.get("age")

    if age < 14:
        msg = "Sorry, you must be atleast 14 years old to study with IPC IELTS."
        self.add_error('age', msg)

    if age > 110:
        msg = "You entered a date of birth outside of the accepted range. Please try again."
        self.add_error('age', msg)

    return data

您还可以在模型或表单上进行验证:

from django.core.validators import MinValueValidator,MaxValueValidator
from django.utils.translation import ugettext_lazy as _

class YourModel(models.Model):
    age = models.DecimalField(..., validators=[
        MinValueValidator(14, message=_("Sorry, you must be atleast 
            14 years old to study with IPC IELTS.")),
        MaxValueValidator(110, message=_("You entered a date of birth outside of the 
            accepted range. Please try again."))
    ])

因此您无需为该字段手动设置样式。

© www.soinside.com 2019 - 2024. All rights reserved.