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
字段中使用了其他驗證器,以及如何實際聲明驗證器。