提交django表单后,POST请求是否包含模型ID?

时间:2018-11-27 16:06:03

标签: django

我有以下django形式:

class AssayCompoundForm(forms.ModelForm):
titrated_compound = forms.ModelChoiceField(queryset=Compound.objects.all())
fixed_compound = forms.ModelChoiceField(queryset=Compound.objects.all())
fixed_concentration = forms.FloatField()

class Meta:
    model = AssayCompound
    fields = ['titrated_compound', 'fixed_compound', 'fixed_concentration']

和以下HTML:

<form method="POST" enctype="multipart/form-data" id="assay-compound-form">
{% csrf_token %}
<div class="row">
    <div class="col-sm">
        <label class="form-input">Titrated Compound</label>
    </div>
    <div class="col-sm">
        {{ new_assay_compound_form.titrated_compound }}
    </div>
    <div class="col-sm"></div>
</div>
<div class="row">
    <div class="col-sm">
        <label class="form-input">Fixed Compound</label>
    </div>
    <div class="col-sm">
        {{ new_assay_compound_form.fixed_compound }}
    </div>
    <div class="col-sm"></div>
</div>
<div class="row">
    <div class="col-sm">
        <label class="form-input">Fixed Concentration</label>
    </div>
    <div class="col-sm">
        {{ new_assay_compound_form.fixed_concentration }}
    </div>
    <div class="col-sm"></div>
</div>
<input id="assay-compound-form-submit" type="submit" name="add-assay-compound" style="display:none">

此表单生成的request.POST看起来像这样:

<QueryDict: {'csrfmiddlewaretoken': ['blah'], 'titrated_compound': ['3'], 'fixed_compound': ['5'], 'fixed_concentration': ['4'], 'add-assay-compound': ['Submit']}>

我的问题是这样的:用户选择的“ titrated_compound”和“ fixed_compound”是Django分配的模型ID的字符串列表吗?还是它们是由'Compound.objects.all()'生成的有序列表的索引的索引?

1 个答案:

答案 0 :(得分:1)

除非指定to_field_name属性,否则它们是每个模型的主键(默认情况下,Django自动生成的id字段)。选中this ref,您还可以查看the code hereprepare_valueto_python方法特别有趣。