模型中缺少Django manytomany字段

时间:2015-09-23 13:53:33

标签: django django-models

假设我有以下模型

 class Member(models.Model):
        name = ...
        qualities = models.ManyToManyField(ProfessionalQuality, related_name='members')

以下表格:

class CommonMemberForm(forms.ModelForm):
    """This form for gathering common features in both admin and member forms
    """
    class Meta:
        model = Member
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super(CommonMemberForm, self).__init__(*args, **kwargs)
        self.fields['qualities'].validators.append(...)

当我尝试实例化表单时,我得到KeyError:'quality'不在self.fields中。这是为什么? 此代码适用于admin。

处理此类字段的正确方法是什么?

2 个答案:

答案 0 :(得分:0)

试试这个:

class CommonMemberForm(forms.ModelForm):
    """This form for gathering common features in both admin and member forms
    """
    class Meta:
        model = Member
        fields = '__all__'
        widgets = {
          'qualities': forms.CheckboxSelectMultiple()
        }

    def __init__(self, *args, **kwargs):
        super(CommonMemberForm, self).__init__(*args, **kwargs)
        #self.fields['qualities'].widget...

答案 1 :(得分:0)

这对我有用:

class CommonMemberForm(AbstractUser):
    class Meta:
        model = Member
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super(RegularUser, self).__init__(*args, **kwargs)
        self._meta.get_field('qualities').validators = [validate_qualities]