假设我在 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 验证。我该怎么做呢?