How to Create a Checkbox Inside a Dropdown Django

Aug. 11, 2024, 2:11 p.m.

When working with Django forms, creating a user-friendly interface can be a challenge, especially when dealing with multiple selection options. Select2, a powerful jQuery-based library, makes it easier to enhance your forms with features like searchable dropdowns and multi-select checkboxes. In this guide, we'll walk through how to integrate Select2 into a Django project to create a multi-select dropdown with checkboxes.
We will jump straight to the point assuming you already have Django installed and setup

Step 1: Create Your Models

Let's assume you want to allow users to select multiple colors in a form. Start by creating a model for the colors:

# myapp/models.py

from django.db import models

class Color(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name

class Product(models.Model):
    name = models.CharField(max_length=100)
    colors = models.ManyToManyField(Color, blank=True)

    def __str__(self):
        return self.name

Step 2: Create a ModelForm for Your Model

Next, create a form to manage the Product model, including the colors field:

# myapp/forms.py

from django import forms
from .models import Product, Color

class ProductForm(forms.ModelForm):
    colors = forms.ModelMultipleChoiceField(
        queryset=Color.objects.all(),
        widget=forms.CheckboxSelectMultiple,  # This widget can be enhanced with Select2
        required=False
    )

    class Meta:
        model = Product
        fields = ['name', 'colors']

Step 3: Update the Template to Include Select2

In your Django template, include the necessary Select2 CSS and JavaScript files using a CDN:

<!-- templates/myapp/product_form.html -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Product</title>
    
    <!-- Include Select2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

</head>
<body>
    <h2>Create a New Product</h2>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Save</button>
    </form>

    <!-- Include jQuery (required by Select2) -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <!-- Include Select2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

    <!-- Initialize Select2 on the colors field -->
    <script>
        $(document).ready(function() {
            $('#id_colors').select2({
                placeholder: "Select Colors",
                allowClear: true
            });
        });
    </script>
</body>
</html>

Step 4: Create the View and URL

Now, create a view to handle the form submission:

# myapp/views.py

from django.shortcuts import render, redirect
from .forms import ProductForm

def create_product(request):
    if request.method == 'POST':
        form = ProductForm(request.POST)
        if form.is_valid():
            # Save the form, but don't commit to the database just yet
            product = form.save(commit=False)
            
            # Save the product to the database
            product.save()
            
            # Now that the product instance exists, save the M2M relationships
            form.save_m2m()
            
            return redirect('product_success')
    else:
        form = ProductForm()
    
    return render(request, 'myapp/product_form.html', {'form': form})

def product_success(request):
    return render(request, 'myapp/product_success.html')

Setup URLs as needed and visit the page to see the magic.

 

Conclusion

Integrating Select2 into your Django forms can significantly enhance the user experience, especially when dealing with multiple selections. With the ability to add searchable and multi-select dropdowns, Select2 provides a modern, efficient way to manage form inputs.

This tutorial covered the basics of setting up Select2 in a Django project. With further customisation, you can tweak the appearance and functionality of your dropdowns to suit your application's specific needs.

Back