1
自定义验证我有以下型号(简体):自定义窗口小部件
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)
我使用的ModelForm,以允许用户在数据库中添加/编辑Profile
和AnotherThing
项目。 简化版:
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
字段中使用了其他验证器,以及如何实际声明验证器。