error to use ModelSelect2Widget

hi all I’m trying using ModelSelect2Widget
I set redis server which I test and it works. then I set the following project:

models.py

class Doctor(models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE)
    status=models.BooleanField(default=True)
    def __str__(self):
        return "{} ({})".format(self.user.first_name,self.department)

class Patient(models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE)
    assignedDoctorId = models.ForeignKey(Doctor, on_delete=models.CASCADE,related_name='doctor_assigned')
    admitDate=models.DateField(auto_now=True)
    status=models.BooleanField(default=False)
    def __str__(self):
        return self.user.first_name

form.py

class DoctorAssigned(s2forms.ModelSelect2Widget):
  model=models.Doctor,
  queryset= models.Doctor.objects.all().filter(status=True),
  search_field = ["username__istartswith",]

class PatientForm(forms.ModelForm):
    class Meta:
        model=models.Patient
        widgets={'assignedDoctorId': assignedDoctor}

I don’t know how to obtain something similar to project found online


with automatic search bar to find doctor

many many thanks in advance

I modify forms.py as found online in order to have

class BaseAutocompleteSelect(s2forms.ModelSelect2Widget):
    class Media:
        js = ("admin/js/vendor/jquery/jquery.min.js",)

    def __init__(self, **kwargs):
        super().__init__(kwargs)
        self.attrs = {"style": "width: 300px"}

    def build_attrs(self, base_attrs, extra_attrs=None):
        base_attrs = super().build_attrs(base_attrs, extra_attrs)
        base_attrs.update(
            {"data-minimum-input-length": 10, "data-placeholder": self.empty_label}
        )
        return base_attrs
    
class DoctorAutocompleteWidget(BaseAutocompleteSelect):
    empty_label = "-- select doctor --"
    search_fields = ("username__icontains",)
    queryset=models.Doctor.objects.all().filter(status=True).order_by("id")    

class PatientForm(forms.ModelForm):
    assignedDoctorId=forms.ModelChoiceField(queryset=models.Doctor.objects.all().filter(status=True),
                                            widget=DoctorAutocompleteWidget)

but results is an empty list

while using

assignedDoctorId=forms.ModelChoiceField(queryset=models.Doctor.objects.all().filter(status=True),empty_label="Name and Department")

I obtain correct list but the last type doesn’t work as I desire

I’m trying from many hours without solution. Can someone help me?

I just added django-select2 to a test project, and what you’re showing here appears to me to be correct.

The blank select box isn’t going to show any entries. The initial instructions seem to create a box where you need to enter in at least 2 characters before it initiates the search.

Try typing in the first two characters of a name that you know is in your data and see if it shows up in the list.

Additionally, when you type the characters in, you should start seeing GET requests on the server console. Verify that those requests are being issued.

many many thanks Ken Whitesell for your help

I’m retrying but no input are accepted…I try digit letters but nothing is shown

in the url page I have:

{% extends 'hospital/admin_base.html' %}
{% load widget_tweaks %}
{% block content %}

<head>
  <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
  <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  {{ form.media.css }}
</head>
<form method="post">
  {% csrf_token %}
  <div class="container register-form">
    <div class="form">
      <div class="form-content">
        <div class="row">
          <div class="col-md-6">
            <div class="form-group">
              {% render_field patientForm.assignedDoctorId class="select2 form-control" placeholder="Doctor" %}
            </div>
      </div>
     </div>
    </div>
  </div>
</form>
{% endblock content %}

maybe there is something wrong in html page?
how did you test the code?
many many thanks

Quite possible. I see where you’re using a custom tag for the field, that’s always a potentially red flag in my book.

You probably want to try it using the standard rendering, then compare it to what you’re generating to identify the differences.

I followed the example in the Django-select2 Quick-start as written. I didn’t try to mix in any information from any other sources. (Yes, I had to change the model and field names to match the project I am using, but structurally, the code is identical.)

Specifically, in my case (ignoring things like import statements, urls, etc):

models.py

class Author(models.Model):
    name = models.CharField(max_length=20)
    user = models.ForeignKey(User, on_delete=models.PROTECT, default=1)

forms.py

class AuthorForm(forms.ModelForm):
    class Meta:
        model = Author
        fields = ['name', 'user']
        widgets = {'user': UserWidget}

views.py

class AuthorCreateView(CreateView):
    model = Author
    form_class = AuthorForm
    success_url = '/'

author_form.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Add author</title>
    {{ form.media.css }}
    <style>input, select {width: 50%}</style>
</head>
<body>
    <h1>Add a new Author</h1>
    <form method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit">
    </form>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    {{ form.media.js }}
</body>
</html>
```

many thanks

i solve using select2 from html page with the following script

<!-- jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Select2 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<script>
    // In your Javascript (external .js resource or <script> tag)
  $(document).ready(function() {
      $('.js-example-basic-single').select2();
  });

</script>
<script>
   $(document).ready(function() {
    $('.js-example-basic-multiple').select2();
});