How to pass dynamic value for django-filter or django-autocomplete-light ?

To pass dynamic values for Django filters or Django-autocomplete-light, you can use a combination of URL parameters, form inputs, or JavaScript.

Here’s an example of how you can achieve this:

  1. Using URL parameters:
  • Define your URL pattern in urls.py with a parameter placeholder:
path('my_view/<str:dynamic_value>/', views.my_view, name='my_view'),

In your view function, access the dynamic value using the parameter name:

def my_view(request, dynamic_value):
    # Use dynamic_value in your filtering or autocomplete logic
    ...

When generating the URL, pass the dynamic value as an argument:

url = reverse('my_view', args=[dynamic_value])

  1. Using form inputs:
  • Create a form with an input field to capture the dynamic value:
class MyForm(forms.Form):
    dynamic_value = forms.CharField()

In your view function, instantiate the form and access the value:

def my_view(request):
    form = MyForm(request.GET or None)
    if form.is_valid():
        dynamic_value = form.cleaned_data['dynamic_value']
        # Use dynamic_value in your filtering or autocomplete logic
        ...

In your template, render the form and submit it:

<form method="GET" action="{% url 'my_view' %}">
    {{ form }}
    <button type="submit">Submit</button>
</form>

Using JavaScript:

  • Include the necessary JavaScript libraries for autocomplete (e.g., jQuery, Django-autocomplete-light).
  • Create an input field in your template and assign it an ID for JavaScript access:
<input type="text" id="dynamic-input" />

In your JavaScript code, initialize the autocomplete functionality:

$(document).ready(function() {
    $('#dynamic-input').autocomplete({
        // Configure the autocomplete options
        source: '/my_autocomplete_endpoint/',
        // Handle the selected value
        select: function(event, ui) {
            var dynamicValue = ui.item.value;
            // Use dynamicValue in your filtering or autocomplete logic
            ...
        }
    });
});

Create an endpoint in your Django views to handle autocomplete requests:

from dal import autocomplete

class MyAutocomplete(autocomplete.Select2ListView):
    def get_list(self):
        # Retrieve the dynamic values based on the search term
        ...

Map this endpoint in urls.py :slight_smile:

path('my_autocomplete_endpoint/', views.MyAutocomplete.as_view(), name='my_autocomplete_endpoint'),

These approaches allow you to pass dynamic values to Django filters or Django-autocomplete-light and use them in your filtering or autocompletion logic. Choose the method that best suits your specific requirements and use case.