1

目前,我正在构建一个由 django 驱动的 Web 应用程序,用于从主表中显示过滤后的数据。我创建了一个表单,用户将在其中指定他/她的选择,并根据表单值数据(以表格形式)显示。我的问题是我无法从需要多个值的表单字段中获取数据。我正在使用“request.POST.get('fieldname','') 从表单中获取数据,但是对于多个值字段,它正在显示最后一个值。

示例: 如果用户在表单域“模块”中选择第一个、第二个和第四个选项,

request.POST.get('模块','')

只给我第四个选择。我希望我清楚自己。

视图.py

def consisreportgen(request):
if request.method == 'POST':
    form = ConsistencyForm(request.POST or None)
    if form.is_valid():
        form_user_data = ConsistencyForm(request.POST)
        Customer=form.cleaned_data['Customer']
        Components=form.cleaned_data['Components']
        Modules=form.cleaned_data['Modules']
        customername=request.POST.get('Customer','')
        modules_choosen=request.POST.get('Modules','')
        bpc_choosen=request.POST.get('Components','')
        severity=request.POST.get('Severity_level','')
        print(modules_choosen)
        print(customername)
        print(severity)
        print(bpc_choosen)
        return HttpResponseRedirect('/consistency/results/')

else:
    form = ConsistencyForm

return render(request,'consistency/consistency.html', {'form': form})

表格.py

class ConsistencyForm(forms.Form):
Customer=forms.ModelChoiceField(
    label="Customer Name",
    widget=forms.Select,
    queryset=Customer.objects.all(),
    empty_label=None,
    )

Severity_level=forms.ModelChoiceField(
     label="Severity Level",
    widget=forms.Select,
    queryset=Criticality.objects.all(),
    empty_label=None,
    )

query_status=forms.ModelChoiceField(
    widget=forms.Select,
    label="Query Status",
    queryset=Status.objects.all(),
    empty_label=None,
    help_text="</br>"
   )


Modules=forms.ModelMultipleChoiceField(
     label="Business Module",
    widget=forms.CheckboxSelectMultiple,
    queryset=Modules.objects.all(),
    )

Components=forms.ModelMultipleChoiceField(
    widget=forms.CheckboxSelectMultiple,
    queryset=Component.objects.all(),
    )

模板文件

 {% extends 'home/base.html' %}
 {% block title %}Consistency Report {% endblock %}

 {% block content %}

 <form action=" " method="post">
 {% csrf_token %}
{{ form }} 
<br />
<input type="submit" value="Generate Report" />

</form>
{% endblock %}
4

1 回答 1

4

您必须使用“getlist”方法:

request.POST.getlist('Modules')

看:

于 2014-11-27T12:48:50.120 回答