Searchable DropDown with crispy Form in Django

Question:

Does anyone know how to add a searchable dropdown box in a form that uses crispy?

views.py:

class GroupMemberPermissionUpdateView(UpdateView):
    
    model = AadGroupmember
    fields = ['id_aadgroup','id_aaduser']
    template_name = 'modify_layout.html'
    success_url = lazy(reverse, str)("permissions_groupmembers")

modify_layout.html:

{% extends 'layout.html' %}

{% load crispy_forms_tags %} 

{% block content %}

<div class="container">
    <div class="row justify-content-center">
      <div class="col-8">
        <h1 class="mt-2">Form for Update</h1>
        <hr class="mt-0 mb-4">


  <form method="POST" enctype="multipart/form-data">
    <!-- Security token -->
      {% csrf_token %}
 
    <!-- Using the formset -->
    {{ form |crispy}} 

      <button type="submit" class="btn btn-primary">Submit</button>
 </form>

    </div>
  </div>
</div>

{% endblock %}

I am having trouble since I am using using crispy and bootstrap v.5.2 for the forms.

Asked By: user19632683

||

Answers:

You can use deselect.js library to solve this. Get the CDN of this library and add it in the appropriate file such as base.html or layout.html

{% extends 'layout.html' %}

{% load crispy_forms_tags %} 

{% block content %}

<div class="container">
    <div class="row justify-content-center">
      <div class="col-8">
        <h1 class="mt-2">Form for Update</h1>
        <hr class="mt-0 mb-4">


  <form method="POST" enctype="multipart/form-data">
    <!-- Security token -->
      {% csrf_token %}
 
    <!-- Using the formset -->
    {{ form |crispy}} 

      <button type="submit" class="btn btn-primary">Submit</button>
 </form>

    </div>
  </div>
</div>

<script>

    dselect(document.querySelector('#id_dropdown_name'), {

        search: true
    });

</script>

{% endblock %}

To get the id of your dropdown, you can inspect the page, django creates the id for html using the model field name e.g if your dropdown name is countries, then the id in the form will be id_countries.

UPDATE:

I have created a simple django app as an example to demonstrate the above explanation django-crispy-searchable-dropdown

Answered By: Mathews Musukuma