2

I am starting to use DAL, but I cannot use the default behavior that set the value to the PKs of the objects in my queryset. So I overriden the 'get_result_value' function to set a custom field as the value of my options.

class CategoryAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):
        country = Agent.get_user_country(self.request.user)
        if not self.request.user.is_authenticated():
            return Category.objects.none()
        qs = Category.objects.filter(country=country)
        if self.q:
            qs = qs.filter(full_category__icontains=self.q)
        return qs

    def get_result_value(self, result):
        return result.special_key

My issue is that when I submit I get this ModelChoiceField error:

Select a valid choice. That choice is not one of the available choices.

Here is the Form:

class OnsiteCategoryForm(forms.Form):
    category = forms.ModelChoiceField(queryset=Category.objects.all(), required=True,
                                      widget=autocomplete.ModelSelect2(url='category_autocomplete'))

Do you have any idea of what could be causing this error ? Thanks

MiniYuuzhan
  • 108
  • 3
  • 14

1 Answers1

3

Well, this is not meant to be a full answer but I'm exactly on your same search track and your Q put me in a "almost-working-direction".

By this I mean that I implemented the get_result_value as per your code and I can get the new value (which in my case is a slug) with JS in the template listening to the select2:select event.

$('select').on('select2:select', function (event) {
  console.log(event.params.data.id);
}

my views.py:

class DjProfileAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):
        qs = DjProfile.objects.all()
        return qs.filter(name__icontains=self.q) if self.q else qs

    def get_result_value(self, result):
        return result.slug

def home(request):
    return render(request, 'home.html', {'form': HomeForm()})

my forms.py:

class HomeForm(forms.Form):
    dj_name = forms.ModelChoiceField(
        queryset=DjProfile.objects.all(),
        widget=autocomplete.ModelSelect2(
            url='dj-autocomplete',
            attrs={
                # Set some placeholder
                'data-placeholder': 'Trova Dj',
                # Only trigger autocompletion after 3 characters have been typed
                'data-minimum-input-length': 3,
            },
        )
    )

Note that in the above jQuery snippet I still refer to id, but now the event.params.data.id attribute contains the slug ...

davideghz
  • 3,596
  • 5
  • 26
  • 50
  • Yes you refer to data.id because id here refers to the html tag's id. Do you have the same error as me ? "Select a valid choice. That choice is not one of the available choices." – MiniYuuzhan Jul 27 '17 at 03:46