0

I like to create a text search field based on dropdown options from a model. I chose django-select2 but it isn't working. This is the output HTML

 <form class="add_new container" method="post">
    <h3 class="text-center">Issue Book</h3><hr><br>
    {% csrf_token %}
    <h4> Choose the student to issue book to</h4><br>
    {% for field in form %}
        {{ field }}
    {% endfor %}<hr><br>
    <input type="submit" value="Issue" class="btn btn-dark text-right" style="float:right">
  </form>

This is the form

class NewIssueForm(forms.ModelForm):
    def __init__(self,*args, pk,school,issuer, **kwargs):
        super(NewIssueForm, self).__init__(*args, **kwargs)
        self.fields['issuer'].initial = issuer
        self.fields['borrower_id'].queryset = Student.objects.filter(school=school)
        self.fields['book_id'].initial = pk #Sets the field with the pk and it's hidden again
    class Meta:
        model = Issue
        fields = ['issuer','book_id','borrower_id']
        widgets = { }
        widgets = {
            'book_id':forms.TextInput(attrs={"class":'form-control','type':'hidden'}),
            'issuer':forms.TextInput(attrs={"class":'form-control','type':'hidden'}),
            'borrower_id': Select2Widget,
        }

Settings.py hs the following

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
    'select2': {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/2",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}
fakeMake
  • 738
  • 8
  • 18
  • Can you add more details what is not working? Any specific error message, or a description you expect and what outcome you get instead? – sk1p May 29 '21 at 09:26
  • There is nothing showing ... It's the normal dropdown, as if it were this code borrower_id':forms.Select(attrs={"class":'form-control','label':'Student'}), – fakeMake May 29 '21 at 09:29

1 Answers1

2

There are multiple parts that need to be set up to make django-select2 work:

  1. jQuery needs to be included in your template. It is not included with django-select2, so you need to provide your own. If this is missing, you will get an error in your browser's developer tools.
  2. The form media needs to be included on the page. Without {{ form.media.css }} in the header, you won't get any of the custom styling, and without {{ form.media.js }} somewhere (for example at the bottom of the <body>), you won't get any of the custom behavior.
  3. django_select2.urls needs to be included in your URL config. Without it, you will probably get an error when select2 tries to resolve URLs, so you probably got that one right.

See also the official documentation of django-select2.

sk1p
  • 6,645
  • 30
  • 35