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

Cannot use DAL in a form without a model #1241

Closed andreccorrea closed 3 years ago

andreccorrea commented 3 years ago

Hi,

I'm trying to use DAL in a ListView, with a formMixin, with a form that doesn't have a model, but it doesn't work. It doesn't render the widget as a Select2.

class MercadoriaFiltroIndexForm(forms.Form):

    busca = forms.ChoiceField()

    class Meta:

        widgets = {
            'busca': autocomplete.Select2(
                url='/estoque/retornar_mercadorias/',
                attrs={
                    'data-placeholder': 'Selecione uma mercadoria',
                    'data-minimum-input-length': 2,
                    'data-theme': 'bootstrap4',
                }
            )
        }

    def __init__(self, *args, request_data=None, **kwargs):
        super(MercadoriaFiltroIndexForm, self).__init__(*args, **kwargs)
        self.fields['busca'].initial = request_data.GET.get('busca', '')

class MercadoriaListView(FormMixin, SuccessMessageMixin, ListView):
    model = Produto
    form_class = MercadoriaFiltroIndexForm
    template_name = 'estoque/cm310_mercadorias/index.html'
    context_object_name = 'mercadorias'
    paginate_by = 5
    ordering = '-id'

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs.update(request_data=self.request)
        return kwargs

class RetornarMercadorias(autocomplete.Select2QuerySetView):
    """Retorna as mercadorias para preencher o combo do select2 com AJAX"""

    def get_queryset(self):

        mercadorias = Produto.objects.all()

        if self.q:
            mercadorias = mercadorias.filter(
                Q(descricao__icontains=self.q) |
                Q(referencia__icontains=self.q) |
                Q(sku__exact=self.q) |
                Q(ean__exact=self.q)
            ).order_by('-id')

        return mercadorias
andreccorrea commented 3 years ago

Nevermind. Just figured it out. I had to use it in the form this way.

class MercadoriaFiltroIndexForm(forms.Form):

    busca = forms.ChoiceField(
        widget=autocomplete.Select2(
            url='/estoque/retornar_mercadorias/',
            attrs={
                'data-placeholder': 'Selecione uma mercadoria',
                'data-minimum-input-length': 2,
                'data-theme': 'bootstrap4',
            })
    )