Can't query with Select2 in Django

I try to use Select2 API for JQuery, but I’m having issues with displaying the returned results. I want to be able to search the results I’m getting from my Ajax request.

It gives me 0 errors, and I believe I followed the documentation correctly. When I log the returned data from the Ajax I also get the correct data back.

What am I doing wrong that I can’t see the results inside the select2 input field when searching?

This is my Jquery code:

$('.radiocheck2').on("click", function(){
    console.log("test");
    $('.nummerplaat').select2({
        minimumInputLength: 2,
        placeholder: 'Nummerplaat',
        dataType: 'json',
        ajax: {
            url:getallnummerplaten,
            method: 'GET',
            data: function (params) {
                return {
                  q: params.term,
                  type: 'public' // search term
                };
            },
            beforeSend: function(xhr, settings) {
                if(!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            },
            processResults: function (data) { 
                arrNummerplaten = []
                 for(i=0; i < data['nummerPlaten'].length; i++){
                     arrNummerplaten[i] = data['nummerPlaten'][i].nummerPlaat
                }

                console.log(arrNummerplaten)

                return {
                  results: arrNummerplaten,
                };
            },
            cache: true
        }
    });
})

This is my Django view to retrieve the data:

class getAllNummerplaten(LoginRequiredMixin, View):
    def get(self, request, *args, **kwargs):
        
        nummerPlaten = list(Voertuigen.objects.all().values("nummerPlaat"))
        print(nummerPlaten)

        nummerPlatenjson = json.dumps(nummerPlaten)

        return JsonResponse({'nummerPlaten': nummerPlaten })

And this is my template code:

<!-- TestCode -->
                    <div style="display:none" id="overzichttankbeurten" class="card shadow mb-4">
                        <div class="card-header py-3">
                            <h6 class="m-0 font-weight-bold text-primary">Manueel toevoegen</h6>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                                    <thead>
                                        <tr>
                                            <th>Nummerplaat</th>
                                            <th>Chauffeur</th>
                                            <th>Datum</th>
                                            <th>Uur</th>
                                            <th>Brandstof</th>
                                            <th>Volume</th>
                                            <th>Prijs</th>
                                            <th>Bedrag</th>
                                            <th>Kilometerstand</th>
    
                                            <th>Acties</th>
                                        </tr>
                                    </thead>
                                    <tbody id="tableplswerk">
                                        <tr>
                                            <td><input class="form-control nummerplaat" placeholder="Nummerplaat" type="text"></td>
                                            <td><input class="form-control" placeholder="Chauffeur" type="text"></td>
                                            <td><input class="form-control" type="date"></td>
                                            <td><input class="form-control" type="time"></td>
                                            <td><input class="form-control" placeholder="Brandstof" type="text"></td>
                                            <td><input class="form-control" placeholder="Volume" type="number"></td>
                                            <td><input class="form-control" placeholder="Prijs" type="number"></td>
                                            <td><input class="form-control" placeholder="Bedrag" type="number"></td>
                                            <td><input class="form-control" placeholder="Kilometerafstand" type="number"></td>
                                            
                                            <td>
                                                <a href=""><i class="fas fa-plus"></i></a>
                                                <!--
                                                <a href=""><i class="fa fa-pencil"></i></a>
                                                <a href="#" data-url="" class="deletefactuur" data-toggle="modal" data-target="#dynamic-modal"><i class="fa fa-trash"></i></a>
                                                -->
                                            </td>
                                        </tr>
                                    
                                    </tbody>
                                </table>
                            </div>
                        </div>                    
                    </div>

I’m not all that familiar with trying to implement select2 directly, so there’s not a lot of explicit help I can provide here - but there are some things I can think for you to check.

First, I think the easiest way to do this is to add the django-select2 package on the server side. It helps avoid a lot of the missteps that occur when trying to integrate this.

But beyond that, you’re passing a search parameter in through your get, but I don’t see where you’re using it. It appears that you’re going to return all values from the Voertuigen model every time it’s called.

What are you seeing in the print statement after the query? (I would be expecting to see it return a list of dicts.)

The Select2 widget is expecting data to be returned in a very specific format - see The Select2 data format | Select2 - The jQuery replacement for select boxes. It does not appear to be the format that you are either sending from the server or creating in your AJAX call.

You might want to log the data that you’re seeing in your processResults function to ensure that you’re getting what you think you’re getting, or producing what needs to be created.

I’m trying to do it with JQuery, unless you know how you can have 2 different form classes inside 1 view?

I want to create 2 views with the same path each with their own form:
View File:

#============= Invoegen Facturen ===============#       
class insertFacturen(LoginRequiredMixin, FormView):
    model = Facturen
    template_name = 'facturen/factureninvoegen.html'
    form_class = FacturenInvoegenForm
    
    def form_valid(self, form):
        form.save()
        # messages.success(self.request, 'Organizer created.')
        return redirect('overzichtfacturen')
    
    def form_invalid(self, form):
        return redirect('insertfacturen')

class manueelToevoegen(LoginRequiredMixin, FormView):
    model = Info
    template_name= 'facturen/factureninvoegen.html'
    tankbeurt_class = TankbeurtenInvoegenForm

My forms.py:

class TankbeurtenInvoegenForm(forms.ModelForm):
    class Meta:
        model = Info
        fields = ['voertuig', 'transactieDatum', 'uur', 'brandstofNaam', 'hoeveelheid', 'prijsPerEenheid', 'nettoBedrag', 'kilometerStand', 'chauffeurReferentie']


        widgets = {
            'voertuig' : s2forms.ModelSelect2Widget(model=Voertuigen, attrs={'data-placeholder':_("Nummerplaat")}, search_fields = ['nummerPlaat__icontains']),
            'brandstofNaam': s2forms.ModelSelect2Widget(model=Brandstoffen, attrs={'data-placeholder':_("Brandstof")}, search_fields = ['brandstofNaam__icontains']),
            'chauffeurReferentie': s2forms.ModelSelect2Widget(model=Chauffeurs, attrs={'data-placeholder':_("Referentienummer")}, search_fields = ['code__icontains'])
        }

class FacturenInvoegenForm(forms.ModelForm):
    class Meta:
        model = Facturen
        fields = ['datumFactuur', 'leverancierRef', 'factuurNummer', 'privaatTankstation', 'eigenOpslag']

        widgets = {
            'leverancierRef' : s2forms.ModelSelect2Widget(model = Leveranciers, attrs={'data-placeholder':_("Ondernemings Nummer")} , search_fields = ['ondernemingsNummer__icontains'])
        }

My template code:

<!-- TestCode -->
                    <div id="overzichttankbeurten" class="card shadow mb-4">
                        <div class="card-header py-3">
                            <h6 class="m-0 font-weight-bold text-primary">Manueel toevoegen</h6>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                                    <thead>
                                        <tr>
                                            <th>Nummerplaat</th>
                                            <th>Chauffeur</th>
                                            <th>Datum</th>
                                            <th>Uur</th>
                                            <th>Brandstof</th>
                                            <th>Volume</th>
                                            <th>Prijs</th>
                                            <th>Bedrag</th>
                                            <th>Kilometerstand</th>
    
                                            <th>Acties</th>
                                        </tr>
                                    </thead>
                                    <form action="{% url 'manueelToevoegen' %}" method="POST">
                                    {% csrf_token %}
                                    <tbody id="tableplswerk">
                                        <tr>
                                            <td>{% render_field form.voertuig class="form-check" %}</td>
                                            <td><input class="form-control chauffeur" placeholder="Chauffeur" type="text"></td>
                                            <td><input class="form-control" type="date"></td>
                                            <td><input class="form-control" type="time"></td>
                                            <td><input class="form-control brandstof" placeholder="Brandstof" type="text"></td>
                                            <td><input class="form-control" placeholder="Volume" type="number"></td>
                                            <td><input class="form-control" placeholder="Prijs" type="number"></td>
                                            <td><input class="form-control" placeholder="Bedrag" type="number"></td>
                                            <td><input class="form-control" placeholder="Kilometerafstand" type="number"></td>
                                            
                                            <td>
                                                <a href=""><i class="fas fa-plus"></i></a>
                                                <!--
                                                <a href=""><i class="fa fa-pencil"></i></a>
                                                <a href="#" data-url="" class="deletefactuur" data-toggle="modal" data-target="#dynamic-modal"><i class="fa fa-trash"></i></a>
                                                -->
                                            </td>
                                        </tr>
                                    
                                    </tbody>
                                    </form>
                                </table>
                            </div>
                        </div>                    
                    </div>

Still not working though…

That’s the purpose of the forms prefix facility.

I’m not seeing how this relates to the Select2 issue though.