Pass request to django-filters custom widget

37 Views Asked by At

I'm trying to create a filter like the one in the image below (from Fiverr), it is a combination of select with options as inputs, enter image description here

I was able to create the widget and select an option and send its sub-input values on submit, but after the loading the values are gone and no option is selected, because the radio select value is not specified by the field so i need to get it directly from the request.GET, but i couldn't pass the reqeust to the widget, i'm seeing it on the Filter class but not in widget.

My Custom Filter: `class PriceFilter(Widget): template_name = 'widgets/PriceFilter.html'

def __init__(self, attrs=None, min=0, max=5000, *args, **kwargs):
    self.min = min
    self.max = max
    # print(self.request)
    print(kwargs)
    super(PriceFilter, self).__init__()  


def get_context(self, name, value, attrs=None, *args, **kwargs):
    context = super().get_context(name, value, attrs)
    context['min'] = self.min
    context['max'] = self.max
    print(self.request)
    print(kwargs)
    return context`

My widget template `

<div class="btn-group">
    <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuClickableInside"
        data-bs-toggle="dropdown" data-bs-auto-close="outside" aria-expanded="false">
        Clickable inside
    </button>
    <ul class="dropdown-menu" aria-labelledby="dropdownMenuClickableInside">
        <div class="form-check">
            <input class="form-check-input" type="radio" name="{{widget.name}}__selector"
                id="{{widget.name}}__selector" #if request.GET.price__selector==1 then ceck this#>
            <label class="form-check-label" for="{{widget.name}}__selector">
                Default radio
            </label>
            <div class="input-filters">
                <input type="hidden" name="{{widget.name}}__lt" id="id_{{widget.name}}__lt"
                    value="{{widget.value|default_if_none:''}}">
            </div>
        </div>
    </ul>
</div>

`

My Filter

`class ListFilter(django_filters.FilterSet): price = django_filters.NumberFilter(widget=PriceFilter())

class Meta:
    model = MainModel
    fields = {
            'name':['contains'],'price':[]
        }

def __init__(self, *args, **kwargs):
    print('kwgs')
    # print(args[0])
    self.request = kwargs.pop('request', None)
    super(ListFilter, self).__init__(*args, **kwargs)
    self.filters["price"].request = args[0]

`

1

There are 1 best solutions below

0
El hosayn Ait Ali On

I was able to solve the problem by specifying the request for the widget on the init function of my Filter Model

class ListFilter(django_filters.FilterSet):
....

def __init__(self, *args, **kwargs):
    self.request = kwargs.pop('request', None)
    super(ListFilter, self).__init__(*args, **kwargs)
    self.filters["price"].extra['widget'].request = args[0]