2012-02-13 99 views
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,以允许用户在数据库中添加/编辑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) 

作为另一个验证我需要检查Locationis_ok == True保存之前。我可以轻松地在ModelForm中为每个项目执行此操作,但代码在每种情况下都是相同的,并打破DRY。我怎样才能将它添加到每个窗体而不用为它写两次代码?是否有可能将验证程序附加到小部件?

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

回答

6

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

相关问题