为什么我的django表格无效?

时间:2018-08-20 04:48:34

标签: python django

我创建我的表单

角色是单选按钮,团队是复选框

class OrganizationMemberForm(forms.ModelForm):
    ROLES = (('member','member'), ('admin','admin'),('manager','manager'),('owner','owner'))
    role = forms.TypedChoiceField(
        choices=ROLES,
        widget=forms.RadioSelect,
    )
    teams = forms.MultipleChoiceField(
        widget=forms.CheckboxSelectMultiple,
    )

    class Meta:
        model = OrganizationMember
        fields = ['role']

在我看来,我添加团队字段是因为我需要choices

def get_form(self, form_class=None):
    form_class = super(OrganizationMembersDetailView, self).get_form(form_class=None)

    TEAMS = [(team.id, team.id) for team in Team.objects.filter(
        organization=self.model.objects.get(id=self.kwargs.get('pk')).organization)]

    form_class.fields['teams'] = forms.MultipleChoiceField(
    choices=tuple(TEAMS),
    widget=forms.CheckboxSelectMultiple,
    )
    return form_class

当我用手测试时,self.request.POST

<QueryDict: {'csrfmiddlewaretoken': ['IMkErNAgdNHHcqeisIQclkHvfqwIbR0ycW6ztlvvZ9cufvulmPOlRKQd8PPr4JFe'], 'role': ['admin'], 'teams': ['1', '3']}>

所以,我要进行单元测试

类OrganizationMemberTest(UserAccountLoginMixin):

def test_change_member_role(self):
    response = self.client.post(
        reverse(
            'organization-member-detail',
            kwargs={'slug': self.organization_obj.name, 'pk': self.user_obj.id}
        ),
            {'role':'admin', 'teams':["1","3"]}
    )
    self.assertEqual(response.status_code, 200)

def test_organization_member_form(self):
    form_data = {'role':'admin', 'teams':['1', '3']}
    form = OrganizationMemberForm(data=form_data)
    self.assertTrue(form.is_valid())

但是测试失败,因为表格无效。

我更改了teams数据

// str -> list
data = {'role':'admin', 'teams':['1','3']}

但表格也无效。

为什么我的表格无效?谢谢:)

更新

IN form.errors Select a valid choice. That choice is not one of the available choices.

当我在get_form中打印(TEAMS)

[(9, 9)]已打印,所以我将值更改为1-> 9

    def test_organization_member_form(self):
    form_data = {'role':'admin', 'teams':['9']}
    form = OrganizationMemberForm(data=form_data)
    self.assertTrue(form.is_valid(), form_error)

但是它有同样的错误...

0 个答案:

没有答案