假设我在models.py中定义了这个模型:
[ . . . ]
class Robot(models.Model):
ROBOT_CATEGORIES = (
[ . . . ]
)
name = models.CharField(max_length=30)
version = models.ForeignKey('Version')
category = models.CharField(max_length=10, choices=ROBOT_CATEGORIES)
comments = models.CharField(max_length=2000, blank=True)
def __unicode__(self):
return "ROBOT %s [%s]" % (self.name, self.version)
class Meta:
unique_together = ('name', 'version',)
我想为此模型添加管理功能。用户可以输入不同机器人名称的逗号分隔列表,save_model
负责将它们保存为不同的对象。为此,我想自己做所有验证。所以这是管理员代码:
class RobotForm(forms.ModelForm):
name = forms.CharField()
comments = forms.CharField(widget=forms.Textarea, required=False)
def clean_name(self):
# custom validation here
[ . . . ]
return data
def clean(self):
cleaned_data = super(RobotForm, self).clean()
# custom validation here
[ . . . ]
return cleaned_data
class Meta:
model = Robot
class RobotAdmin(admin.ModelAdmin):
form = RobotForm
list_display = ('name','version','category','comments')
def save_model(self, request, obj, form, change):
# custom save method
obj.save()
admin.site.register(Robot, RobotAdmin);
除了我在max_length
模型中设置的Robot.name
限制外,一切正常。在'添加'表单,如果列表的长度在'名称'字段超过30个字符,它会闪烁错误。我在clean_name
方法中验证每个个人姓名的长度,并希望在表单字段中禁用max_length验证。我该怎么做?
答案 0 :(得分:1)
在重写的clean方法中,从clean_data中删除错误,如下所示: