2012-02-13 149 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屬性定義爲您的自定義小部件。然後,您可以簡單地在任何表單中引用該字段。

相關問題