Reputation: 421
I am pulling my hair out over this...all other SO questions relate to ModelChoiceField
and that is not what I need.
So I have a lookup table in a SQL database that contains an ID and a keyword. This table is NOT UNIQUE meaning keywords can be duplicated but IDs are still unique. This means I cannot use ModelChoiceField
since I want to populate it with unique keywords and using it will result in returning duplicated keywords.
Thus, I tried using ChoiceField
and instantiating the choices in my class form as so:
def unique_values():
return keyword.objects.order_by('keyword').values_list('keyword',
'keyword').distinct()
class CustomForm(forms.Form):
keywords = forms.ChoiceField(choices=unique_values,
widget=Select2MultipleWidget)
This works in populating the dropdown list form in my Class Based view. but when I select and submit the form, I get the result: Select a valid choice. ['(*INSERT KEYWORD NAME*)'] is not one of the available choices.
. How do I get around this?
EDIT: Sytech's answer in the comments solved this.
Upvotes: 0
Views: 739
Reputation: 40861
You can use a ModelChoiceField
here no problem. Just use an appropriate queryset that returns the unique keyword objects.
For example, you can use the following queryset when using postgres
...
keyword = forms.ModelChoiceField(queryset=keyword.objects.distinct('keyword'))
...
Upvotes: 1