如果在各个字段中相互依赖时,如何在管理员中应用验证?
e.g。假设我有一个字段A(BooleanField)和字段B(字段B),我想要做的是,如果在管理员用户中选择字段A(复选框)并且不在字段B中输入任何内容 如果他试图保存,它应该抛出一个像正常空白= False给出的错误。那么我怎样才能在admin中进行这种验证。
例如用例
我有一张具有以下结构的表: -
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)
在管理员中,如果我选择重新访问的复选框,并在字段interview_type中显示(如果用户从该下拉菜单中选择了“无”,则会显示选项为“无”,“配对访问”,“时间序列”的下拉菜单),然后按“保存”按钮抛出一个像正常空白的错误= False显示,说“这个字段是必需的”
如何在字段相互依赖的情况下进行此类验证?
请忽略语法错误。
由于
答案 0 :(得分:0)
我在response_change中感到困惑并且覆盖了干净的方法,最后这就是我所做的
类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 ....