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

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

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(1)
刘奇

We can test it using the code:
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

As a test, we insert three rows of data into the table:

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')

In the above form, we created ModelChoiceField and ModelMutipleChoiceField. In queryset, we query objects with id less than or equal to 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>

We fill in the form as follows.

The output result is:

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

It can be seen from this:
ModelChoiceField returns the value through cleaned_data to the instance of the model corresponding to the corresponding queryset.
ModelMultipleChoiceField returns a list of instances of the model corresponding to the corresponding queryset through cleaned_data.
Other forms use cleaned_data to return the value to define the type of its field.
The documentation in Django is very clear, you can read it carefully.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template