App works with ModelChoiceField but does not work with ModelMultipleChoiceField

191 views Asked by At

I am trying to retrieve user input data in a django page. But I am unable to choose to multichoice field. I have tried multiple alternatives to no relief.

  • self.fields['site'].queryset=forms.ModelMultipleChoiceField(queryset=sites.objects.all())

  • self.fields['site'] = forms.ModelChoiceField(queryset=sites.objects.filter(project_id=project_id))

  • self.fields['site'].queryset = forms.MultipleChoiceField(widget=forms.SelectMultiple, choices=[(p.id, str(p)) for p in sites.objects.filter(project_id=project_id)])

forms.py

class SearchForm(forms.Form):

class Meta:
    model= images
    fields=['site']

def __init__(self,*args,**kwargs):
    project_id = kwargs.pop("project_id")     # client is the parameter passed from views.py
    super(SearchForm, self).__init__(*args,**kwargs)
    self.fields['site'] = forms.ModelChoiceField(queryset=sites.objects.filter(project_id=project_id))

views.py

def site_list(request, project_id):

form = SearchForm(project_id=project_id)
site_list = sites.objects.filter(project__pk=project_id).annotate(num_images=Count('images'))
template = loader.get_template('uvdata/sites.html')

if request.method == "POST":
    image_list=[]
    form=SearchForm(request.POST,project_id=project_id)
    #form=SearchForm(request.POST)
    #site_name=request.POST.get('site')
    if form.is_valid():
        site_name=form.cleaned_data.get('site')
        print(site_name)

I expect to get a multiselect field but I end up getting this error:

Exception Value:

'site'

Exception Location: /home/clyde/Downloads/new/automatic_annotator_tool/django_app/search/forms.py in init, line 18 (line 18:self.fields['site'].queryset = forms.MultipleChoiceField(widget=forms.SelectMultiple, choices=[(p.id, str(p)) for p in sites.objects.filter(project_id=project_id)]))

1

There are 1 answers

0
voodoo-burger On

You are not defining your form correctly. The documentation shows you how to do this.

In your case it would be something like this:

class SearchForm(forms.Form):

    site = forms.ModelMultipleChoiceField(queryset=Sites.object.none())

    def __init__(self,*args,**kwargs):
        project_id = kwargs.pop("project_id")
        super(SearchForm, self).__init__(*args,**kwargs)
        self.fields['site'].queryset = Sites.objects.filter(project_id=project_id))

You also appear to be confusing regular Form and ModelForm, as Meta.model is only used in ModelForm whereas you are using a regular Form. I suggest you read up on the difference in the documentation before you proceed.