yourlabs / django-autocomplete-light

A fresh approach to autocomplete implementations, specially for Django. Status: v4 alpha, v3 stable, v2 & v1 deprecated.
https://django-autocomplete-light.readthedocs.io
MIT License
1.79k stars 467 forks source link

autocomplete.ListSelect2 not selecting value #1249

Open David-Keeffe opened 3 years ago

David-Keeffe commented 3 years ago

I'm trying the new separated value/display code in autocomplete.ListSelect2, and I'm finding it hard to pass a value that actually selects the item out of the supplied list. It always shows an empty box. I'm trying to manage a rather convoluted address model, so just using a queryset isn't practical. I have to fill the form with raw textual data so just passing object IDs isn't on. However, we do need the object ID if one matches. .... (I said it was convoluted)

It also seems that the subclass (CareofSelectField) validate isn't getting called.

def getAddresses():
        # Don't forget to filter out results depending on the visitor !
        logging.debug("CO ADDRESS LIST")
        qs = CareofAddress.objects.select_related('address')

        result = []

        for xxx in qs:
            result.append([xxx.id, "%s" % str(xxx)])
        logging.debug("CO ADDRESS: %s" % str(result))
        return result

class CareofSelectField(autocomplete.Select2ListCreateChoiceField):
    def __init__(self, *args, **kwargs):
        logging.debug("CO SELECT INIT")
        super().__init__(*args, **kwargs)

    def validate(self, value):
        logging.debug("CO SELECT VALIDATE %s -> %s" % (str(self), str(value)))
        super().validate(value)

class CareofAddressForm(forms.ModelForm):
    target = forms.CharField(widget=forms.HiddenInput())
    careof = CareofSelectField(
        choice_list=getAddresses(),
        #widget=AutocompleteSelect(AdbCompany._meta.get_field('related').remote_field, admin.site),
        widget=autocomplete.ListSelect2(url='careof-autocomplete'),
        required=False
    )
j-bernard commented 3 years ago

Did you manage to solve your problem? I was having the same issue and solved it by "stringifying" my values (and also field names in my cases).

letoss commented 2 years ago

I'm here with the same issue. It works when I want to create an instance. When I retrieve an existent one, the field is always blank, I have to re-add the option before saving it.