Django: fetching data from form fields that takes multiple values

3.4k views Asked by At

Currently,I am building a django powered web app for displaying filtered data form a master table.I have created a form where user will specify his/her choice and depending upon the form values data( in tabular form) will be displayed. My problem is that I am not able to fetch data from form fields which takes multiple values.I am using "request.POST.get('fieldname','') to fetch data from form, but for multiple values fields , it's displaying the last value.

Example : If user is selecting first, second and fourth option in formfield "Modules",

request.POST.get('Modules','')

is giving me only fourth option. I hope I am making myself clear.

views.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})

forms.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(),
    )

template file

 {% 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 %}
1

There are 1 answers

3
Pascal On BEST ANSWER

You have to use the "getlist" method:

request.POST.getlist('Modules')

See: