class MyModel(models.Model) :
people = models.ManyToManyField(User,related_name='people')
...
class MyForm(ModelForm) :
class Meta :
model = MyModel
widgets = {'people':TextInput(),}
def clean_people(self) :
# turn a comma-separated list of names into a Python list
return [name0,name1,...]
def clean(self) :
# if no other errors, turn list of names into list of Users
这不起作用,因为在调用field.clean之前不会调用clean_people,其中field是ModelMultipleChoiceField的一个实例,它检查Python列表或元组,因此引发ValidationError并跳过clean_people。 是否存在调用顺序的原因,是否存在一些避免此问题的标准规定?我可以在MyForm的每个实例中将field.clean设置为lambda x:x,但这看起来真的很难看。将MyForm中的人员字段明确定义为CharField可能是正确的做法吗?
答案 0 :(得分:0)
你为什么不override clean的行为?
class MyForm(ModelForm):
class Meta:
model = MyModel
widgets = {'people':TextInput(),}
def clean_people(self):
# turn a comma-separated list of names into a Python list
return [name0,name1,...]
# override below!
def clean(self):
super(MyForm, self).clean()
# do stuff you need, eg: call clean_people(self)
return self.cleaned_data
我不确定我是否100%理解你的问题,但仅仅通过在clean()之前定义clean_people()并不意味着之前会调用它,甚至根本不需要调用它。
答案 1 :(得分:0)
class MyModel(models.Model) :
people = models.ManyToManyField(User,related_name='people')
...
class MyForm(ModelForm):
people = CharField(...)
class Meta :
model = MyModel
def clean_people(self) :
# turn a comma-separated list of names into a Python list
return [name0,name1,...]
def clean(self) :
# if no other errors, turn list of names into list of Users