dev_ren
dev_ren

Reputation: 31

How to implement dropdown search bar in Django?

I am thinking of a way how to implement dropdown search bar on my application, this is just the simplest form of it, given:

models.py

CATEGORY = (
    ('Hard Disk Drive', 'Hard Disk Drive'),
    ('Solid State Drive', 'Solid State Drive'),
    ('Graphics Card', 'Graphics Card'),
    ('Laptop', 'Laptop'),
    ('RAM', 'RAM'),
    ('Charger', 'Charger'),
    ('UPS', 'UPS'),
    ('Mouse', 'Mouse'),
    ('Keyboard', 'Keyboard'),
    ('Motherboard', 'Motherboard'),
    ('Monitor', 'Monitor'),
    ('Power Supply', 'Power Supply'),
    ('Router', 'Router'),
    ('AVR', 'AVR'),
    ('Tablet', 'Tablet'),
    ('System Unit', 'System Unit'),
    ('Audio Devices', 'Audio Devices'),
    ('CPU', 'CPU'),
    ('Others', 'Others'),
)
class Product(models.Model):
    model_name = models.CharField(max_length=100, null=True, blank=True)
    asset_type = models.CharField(max_length=20, choices=CATEGORY, blank=True)

forms.py

class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ['model_name', 'asset_type']

views.py

def product(request):
    items = Product.objects.all()
    if request.method == 'POST':
        form = ProductForm(request.POST, request.FILES)
        if form.is_valid():
           form.save()
        else:
           form = ProductForm()

    context = {
        'items': items,
    }
    return render(request, 'products.html', context)

products.html

<div class="container">
    <div class="row my-1">
 
            <h4>Enroll a product:</h4>
            <hr>
    </div>
        
            <form method="POST" enctype="multipart/form-data">
                {% csrf_token %}
                {{ form|crispy }}
                <input class="btn btn-success btn-block" type="submit" value="Add Product">
                <button type="button" class="btn btn-danger btn-block">Close</button>
            </form>
</div>

We all know that the result of the form (in HTML) when showing the categories of the model Product(asset_type) is a dropdown field with no search bar on it. I am worrying that when my categories grow, it will be harder for the user to find the category unless the user can search using the same field where the dropdown exist so that it will filter what will shown on the dropdown every time he/she types.

Upvotes: 0

Views: 3067

Answers (1)

You can consider using django-select2, example, or directly select2

This is how will be show

Upvotes: 1

Related Questions