python - django中外键和多对多表单传入值,取值操作怎么做?
PHP中文网
PHP中文网 2017-04-18 09:25:35
0
1
508

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

PHP中文网
PHP中文网

认证高级PHP讲师

全部回覆(1)
刘奇

我們可以使用程式碼測試一下:
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中的文件中寫的很清楚,你可以仔細看一下。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!