定制小部件的自定义验证

Vir*_*liu 1 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)
Run Code Online (Sandbox Code Playgroud)

我使用的ModelForm允许用户添加/编辑ProfileAnotherThing项目数据库.简化版:

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

class AnotherThingForm(ModelForm):
    class Meta:
        model = Profile
        widgets = {'location': CustomLocationWidget()}
Run Code Online (Sandbox Code Playgroud)

简化的代码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)
Run Code Online (Sandbox Code Playgroud)

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

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

Dan*_*man 6

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