2012-03-31 105 views
0

如何在管理員對各個字段進行驗證時彼此相互依賴?管理員字段依賴於其他字段時的字段驗證

例如假設我有一個字段A(布爾字段)和字段B(字符字段),我想要做的是如果在管理員用戶選擇字段A(複選框),並沒有在字段B中輸入任何內容,並且他試圖保存,它應該拋出一個像正常空白= False給出的錯誤。那麼我如何在管理員中進行這種驗證。

如用例

我有具有以下結構的表: -

INTERVIEW_TYPES =(

('default', 'None'), 
    ('Paired Visit','Paired Visit'), 
    ('Time Series', 'Time Series'), 

), 

類面試(models.Model):

ic_number    = models.CharField(verbose_name ="Visit Configuration Number",max_length=20,unique=True,null =True,blank=True) 
ic_description   = models.TextField(verbose_name ="Visit Configuration Description",null = True,blank=True) 
title     = models.CharField(verbose_name ="Visit Configuration Title",max_length=80,unique=True) 
starting_section  = models.ForeignKey(Section) 
interview_type   = models.CharField(verbose_name = "Mapped Visit",choices=CHOICES.INTERVIEW_TYPES, max_length=80, default="Time Series") 
select_rating   = models.CharField(choices=CHOICES.QUESTION_RATING, max_length=80, default="Select Rating") 
view_notes    = models.CharField(choices=CHOICES.VIEW_NOTES, max_length=80, default="Display Notes") 
revisit    = models.BooleanField(default=False) 

.....等等......

class Meta: 
    verbose_name = 'Visit Configuration' 
    verbose_name_plural = 'Visit Configurations' 
    # ordering = ('rpn_number',) 

def __unicode__(self): 
    return self.title 

其admin.py

類InterviewAdmin(admin.ModelAdmin):

list_display = ('id','title', 'starting_section','ic_number','show_prior_responses') 
raw_id_fields = ('starting_section',) 

admin.site.register(採訪,InterviewAdmin)

在管理,如果我選擇的複選框如果用戶從該下拉列表中選擇無,然後按保存按鈕,它應該拋出我像一個正常的空白錯誤= False顯示重訪和現場interview_type(這將顯示下拉選擇無,配對訪問,時間序列) ,說「T他的領域是必需的「

我怎樣才能做這種類型驗證的領域是相互依賴的?

請忽略語法錯誤是任何。

感謝

回答

0

我糊塗了在response_change和壓倒一切的清潔方法,終於這是我在admin.py

類InterviewAdminForm製作模型的形式(forms.ModelForm做

覆蓋清潔方法):

class Meta: 
    model = Interview 

def clean(self, *args, **kwargs): 
    cleaned_data = super(InterviewAdminForm, self).clean(*args, **kwargs) 

    if self.cleaned_data['interview_type'] == "default" \ 
    and self.cleaned_data['Revisit'] == True: 
     raise forms.ValidationError({'interview_type': ["error message",]}) 
    return cleaned_data 

類InterviewAdmin(admin.ModelAdmin):

# call the form for Validation 
form = InterviewAdminForm 
....and so on .... 

+0

有人可以告訴我,如何顯示錯誤消息就在應用驗證的字段上方。目前是在管理頁面上顯示錯誤消息。我想展示在該領域之上。在這種情況下,它應該位於interview_type字段的上方,比如默認admin在該字段上方顯示「此字段是必需的」。提前致謝 – 2012-03-31 12:52:41