Home > database >  Django Form | Group Model | MultiSelect | getting only single value from the form by using MultiSele
Django Form | Group Model | MultiSelect | getting only single value from the form by using MultiSele

Time:03-15

I am trying to get input from the user in a template, I am showing list of Groups in template available from the Group model in Django Auth Models and expecting multiple values. But it is only returning single value even selecting multiple options

from django.contrib.auth.models import Group

class MyForm(forms.ModelForm):
    
    the_choices = forms.ModelMultipleChoiceField(queryset=Group.objects.all(),
                                                 required=False, 
                                                 widget=forms.CheckboxSelectMultiple)

    class Meta:
        model = Group
        exclude = ['name', 'permissions']

    
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)

views.py

from .forms import MyForm
from django.shortcuts import render
from django.views.generic import View

class see(View):

    def __init__(self):
        pass

    def get(self, request):
        context ={}
        context['form']= MyForm()
        return render(request, "home.html", context)
    
    def post(self, request):
        print(request.POST.get('the_choices'))

        return HttpResponse('Great!')

image references below

Template - Input Form Image

Output in Console

kindly refer to image 2, I expect 1 and 2 (group name preffered) in console but its returning only 2.

CodePudding user response:

If you access request.POST.get('key') (or request.POST['key']), you only get the last value associated with that key.

You access all values with the .getlist(…) method [Django-doc]:

print(request.POST.getlist('the_choices'))

But normally you process data with the form itself, so:

form = MyForm(request.POST, request.FILES)
if form.is_valid():
    print(form.cleaned_data['the_choices'])

This will also clean the data and return model objects, not their primary keys.

CodePudding user response:

use getlist

https://docs.djangoproject.com/en/4.0/ref/request-response/#django.http.QueryDict.getlist

try this

the_choices = request.POST.getlist('the_choices')
  • Related