定制小部件的自定义验证

时间:2012-02-13 10:18:49

标签: django django-forms

我有以下模型(简化):

class Location(models.Model):
    name = models.CharField(max_length=100)
    is_ok = models.BooleanField()

class Profile(models.Model):
    name = models.CharField(max_length=100)
    location = models.ForeignKey(Location)

class AnotherThing(models.Model):
    name = models.CharField(max_length=100)
    location = models.ForeignKey(Location)

我使用模型表单允许用户在数据库中添加/编辑ProfileAnotherThing项。 简化版:

class ProfileForm(ModelForm):
    class Meta:
        model = Profile
        widgets = {'location': CustomLocationWidget()}

class AnotherThingForm(ModelForm):
    class Meta:
        model = Profile
        widgets = {'location': CustomLocationWidget()}

CustomLocationWidget的简化代码是这样的:

class CustomLocationWidget(Input):
    def __init__(self, *args, **kwargs):
        super(CustomLocationWidget, self).__init__(*args, **kwargs)

    def render(self, name, value, attrs = None):
        output = super(CustomLocationWidget).render(name, value, attrs)
        output += 'Hello there!'
        return mark_safe(output)

作为另一项验证,我需要在保存前检查Location是否有is_ok == True。我可以在ModelForm中轻松地为每个项目执行此操作,但代码在每种情况下都相同并且会中断DRY。如何在不为其编写代码的情况下将其添加到每个表单中?是否可以将验证器附加到窗口小部件?

我正在查看default_validators,但我不知道其他验证器用于ForeignKey字段以及如何实际声明验证器。

1 个答案:

答案 0 :(得分:6)

验证存在于字段上,而不是小部件上。如果您需要在一堆表单中进行相同的自定义验证,请定义自定义字段,向包含该验证代码的字段添加clean方法,然后将字段的widget属性定义为你的自定义小部件然后,您可以简单地以任何形式引用该字段。

相关问题