首页 > django中外键和多对多表单传入值,取值操作怎么做?

django中外键和多对多表单传入值,取值操作怎么做?

对于别的类型的表单数据我使用的是cleaned_data['列名']取得传入值,对于ChoiceFieldMultipleChoiceField的传入值取值应当怎么取?如果用cleaned_data['列名']方式取值分别会得到什么样的数据结构?


我们可以使用代码测试一下:
model:

class TestModel(models.Model):

    TYPE_CHOICE = (
        ('1', 'a'),
        ('2', 'b'),
        ('3', 'c')
    )

    name = models.CharField(max_length=5)
    type_choice = models.CharField(max_length=20, choices=TYPE_CHOICE)

    def __unicode__(self):
        return self.name

作为测试,我们在表中插入三行数据:

id|name|type_choice
1|aa|a
2|bb|b
3|cc|c

form:

class IndexForm(forms.ModelForm):
    TYPE_CHOICE = (
        ('1', 'a'),
        ('2', 'b'),
        ('3', 'c')
    )

    test_choice_type = forms.ModelChoiceField(queryset=TestModel.objects.filter(id__lte=2))
    test_multiple_choice_type = forms.ModelMultipleChoiceField(queryset=TestModel.objects.filter(id__lte=2))

    class Meta:
        model = TestModel
        fields = ('name', 'type_choice')

在上面的form中,我们创建了ModelChoiceField跟ModelMutipleChoiceField,在queryset中我们查询id小于等于2的对象。

view:

class IndexView(FormView):
    template_name = 'index.html'
    form_class = IndexForm

    def form_valid(self, form):
        name = form.cleaned_data['name']
        type_choice = form.cleaned_data['type_choice']
        test_choice_type = form.cleaned_data['test_choice_type']
        test_multiple_choice_type = form.cleaned_data['test_multiple_choice_type']

        print type(name), name
        print type(type_choice), type_choice
        print type(test_choice_type), test_choice_type
        print type(test_multiple_choice_type), test_multiple_choice_type

        return super(IndexView, self).form_valid(form)

Template:

<form action="" method="post">
    {% csrf_token %}
    {{ form|as_bootstrap }}
    <button type="submit">提交</button>
</form>

我们在表单中如下填写。

输出结果为:

<type 'unicode'> test
<type 'unicode'> 1
<class 'testdjango.hei.models.TestModel'> 1
<class 'django.db.models.query.QuerySet'> [<TestModel: 1>, <TestModel: 2>]

由此可以看出:
ModelChoiceField通过cleaned_data返回值为相应queryset对应的model的实例。
ModelMultipleChoiceField通过cleaned_data返回值为相应queryset对应的model的实例list。
其他的form痛过cleaned_data返回值为其字段定义类型。
Django中的文档中写的很清楚,你可以仔细看一下。

【热门文章】
【热门文章】