0
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 中的 people 字段明确定义为 CharField 可能是正确的做法吗?

4

2 回答 2

0

你为什么不覆盖 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() 并不意味着它会在之前被调用,甚至根本不会被调用。

于 2013-03-18T17:03:40.937 回答
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
于 2013-03-20T00:53:13.377 回答