Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 9 additions & 13 deletions django_filters/widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,21 +250,17 @@ class QueryArrayWidget(BaseCSVWidget, forms.TextInput):

def value_from_datadict(self, data, files, name):
if not isinstance(data, MultiValueDict):
data = data.copy()
for key, value in data.items():
# treat value as csv string: ?foo=1,2
if isinstance(value, str):
data[key] = [x.strip() for x in value.rstrip(",").split(",") if x]
data = MultiValueDict(data)

values_list = data.getlist(name, data.getlist("%s[]" % name)) or []

# apparently its an array, so no need to process it's values as csv
# ?foo=1&foo=2 -> data.getlist(foo) -> foo = [1, 2]
# ?foo[]=1&foo[]=2 -> data.getlist(foo[]) -> foo = [1, 2]
if len(values_list) > 0:
ret = [x for x in values_list if x]
else:
ret = []
vl=[]
for value in values_list:
# treat value as csv string: ?foo=1,2
if isinstance(value, str):
vl += [ x.strip() for x in value.rstrip(",").split(",") if x]
else:
vl += value


return list(set(ret))
return list(set(vl))
8 changes: 7 additions & 1 deletion tests/test_widgets.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from django.forms import NumberInput, Select, TextInput
from django.test import TestCase
from django.http import QueryDict

from django_filters.widgets import (
BaseCSVWidget,
Expand Down Expand Up @@ -526,11 +527,12 @@ def test_widget(self):
<input type="text" name="price" value="1,2" />""",
)


class QueryArrayWidgetTests(TestCase):
def test_widget_value_from_datadict(self):

w = QueryArrayWidget()


# Values can be provided as csv string: ?foo=bar,baz
data = {"price": None}
result = w.value_from_datadict(data, {}, "price")
Expand Down Expand Up @@ -595,3 +597,7 @@ def test_widget_value_from_datadict(self):

result = w.value_from_datadict({}, {}, "price")
self.assertEqual(result, [])

data = QueryDict("price=1,2")
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't a query array example. 🤔

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The idea is that all input would work, not just QueryArrays. Also ?price=1,2. QueryArray only supports ?price=1,price=2.

result = w.value_from_datadict(data, {}, "price")
self.assertEqual(result, ["1", "2"])