'Django how to render ModelForm field as Multiple choice
I have a model form like this:
from django.forms import widgets
class AdvancedSearchForm(forms.ModelForm):
class Meta:
model= UserProfile
fields = ( 'name', 'location', 'options')
Where 'options' is a list of tuples and is automatically rendered in template as drop down menu. However I want users to be able to choose multiple options in the search form.
I know I need to add a widget to the form class as I looked at the docs and it seems to me that it needs to be something like this to the class:
widgets = {
'options': ModelChoiceField(**kwargs)
}
However I get this error
name 'MultipleChoiceField' is not defined
So Finally could not figure out how exactly to implement that. So appreciate your help.
Solution 1:[1]
ModelChoiceField is not a widget, it's a form field, but to use multiple version of it, you need to override field:
class AdvancedSearchForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(AdvancedSearchForm, self).__init__(*args, **kwargs)
self.fields['options'].empty_label = None
class Meta:
model= UserProfile
fields = ( 'name', 'location', 'options')
then to override the widget to checkboxes, use CheckboxSelectMultiple
widgets = {
'options': forms.CheckboxSelectMultiple()
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | matagus |
