Django Forms: Django-select2 Not rendering multi select box correctly

659 Views Asked by At

I'm using django-select2 : https://django-select2.readthedocs.io/en/latest/index.html

I'm attempting to create a multiple tag select dropdown box similar to this:

https://raw.githubusercontent.com/asyncee/django-easy-select2/master/screenshots/select2_multiple.png

The problem is its not loading as expected and is like this:

https://media.geeksforgeeks.org/wp-content/uploads/20191201114034/django-forms-multiplechoicefield-11.png

Below is my code. Im using the Select2TagWidget currently but I have tried the following other widgets:

ModelSelect2MultipleWidget
Select2MultipleWidget

forms.py

class BankForm(ModelForm):
     required_css_class = "required"
     formField1 = forms.ModelMultipleChoiceField(
       queryset=Bank.objects.all(),
       label="Lead Bank",
       widget=Select2TagWidget,
)

class Meta:
model = AdditionalBank
fields = [
"formField1",
]

""" Labels for the fields we didn't override """
labels = {}

urls.py

Ive added the correct path to my urls.py file

path("select2/", include("django_select2.urls")),

I have the redis queue setup correctly in my settings.py file. Im pretty confident the rest of the configuration is setup correctly outlined in the docs for django-select2

My Front end form is rendering this html/css:

<select name="lead_bank" lang="None" data-minimum-input-length="1" data-theme="default" data-allow-clear="false" data-tags="true" data-token-separators="\[\&quot;,\&quot;, \&quot; \&quot;\]" required="" id="id\_lead\_bank" class="django-select2" multiple="">

<option value="1">Citi</option>

<option value="2" selected="">USBank</option>

<option value="3">Wells Fargo</option>

<option value="4" selected="">NY Bank</option>

</select> 

Keep in mind I am very new to front end dev. Primarily a backend dev.

1

There are 1 best solutions below

0
Mahammadhusain kadiwala On

Here I Created Select2 with ManytoMany like this

models.py

class Category(models.Model):
    name=models.CharField(max_length=200)
    def __str__(self):
        return self.name
    

class Product(models.Model):
    cates=models.ManyToManyField(Category)
    name=models.CharField(max_length=200)
    def __str__(self):
        return self.name

form.py

class ProductForm(forms.ModelForm):
    class Meta:
        model=Product
        fields="__all__"

        widgets = {
            'name':forms.TextInput(attrs={'class':'form-control'}),
            'cates':forms.Select(attrs={'class':'js-example-basic-multiple form-select','multiple':'multiple'}),
        }

views.py

def DemoView(request):
    form = ProductForm()
    context = {'form':form}
    return render(request,'index.html',context)

HTML (base.html)

{% load static %}

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>
    {% block title %}
    {% endblock title %}
  </title>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
</head>

<body>
  <nav class="navbar navbar-expand-lg bg-body-tertiary">
    <div class="container-fluid">
      <a class="navbar-brand" href="#">Navbar</a>
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
        aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      
    </div>
  </nav>


  {% block body %}

  {% endblock body %}

  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
  <script>
    $(document).ready(function () {
      $('.js-example-basic-multiple').select2();
    });
  </script>
</body>

</html>

HTMl (index.html)

<div class="container">
    <div class="row">
        <div class="col p-3">
            {{form.as_p}}
        </div>

    </div>
</div>

browser Output

enter image description here

enter image description here