Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

QuerySelectField: Add support for blank choice when using groups #53

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
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
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ classifiers = [
]
requires-python = ">=3.9"
dependencies = [
"WTForms>=3.1",
"WTForms>=3.1.2",
"SQLAlchemy>=1.4",
]
dynamic = ["version"]
Expand Down
8 changes: 7 additions & 1 deletion src/wtforms_sqlalchemy/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,9 +147,12 @@ def _get_object_list(self):
self._object_list = list((str(get_pk(obj)), obj) for obj in query)
return self._object_list

def _get_blank_choice(self):
return (self.blank_value, self.blank_text, self.data is None, {})

def iter_choices(self):
if self.allow_blank:
yield (self.blank_value, self.blank_text, self.data is None, {})
yield self._get_blank_choice()

for pk, obj in self._get_object_list():
yield (pk, self.get_label(obj), obj == self.data, self.get_render_kw(obj))
Expand All @@ -159,6 +162,9 @@ def has_groups(self):

def iter_groups(self):
if self.has_groups():
if self.allow_blank:
yield (None, [self._get_blank_choice()])

groups = defaultdict(list)
for pk, obj in self._get_object_list():
groups[self.get_group(obj)].append((pk, obj))
Expand Down
110 changes: 98 additions & 12 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,20 @@ def __call__(self, field, **kwargs):
)


class LazyGroupSelect:
def __call__(self, field, **kwargs):
return list(
(
group,
list(
(val, str(label), selected, render_kw)
for val, label, selected, render_kw in choices
),
)
for group, choices in field.iter_groups()
)


class Base:
def __init__(self, **kwargs):
for k, v in iter(kwargs.items()):
Expand Down Expand Up @@ -83,7 +97,7 @@ def _do_tables(self, mapper, engine):
mapper_registry.metadata.create_all(bind=engine)

def _fill(self, sess):
for i, n in [(1, "apple"), (2, "banana")]:
for i, n in [(1, "apple"), (2, "banana"), (3, "apricot")]:
s = self.Test(id=i, name=n)
p = self.PKTest(foobar=f"hello{i}", baz=n)
sess.add(s)
Expand Down Expand Up @@ -117,7 +131,12 @@ class F(Form):
self.assertTrue(form.a.data is not None)
self.assertEqual(form.a.data.id, 1)
self.assertEqual(
form.a(), [("1", "apple", True, {}), ("2", "banana", False, {})]
form.a(),
[
("1", "apple", True, {}),
("2", "banana", False, {}),
("3", "apricot", False, {}),
],
)
self.assertTrue(form.validate())

Expand Down Expand Up @@ -155,11 +174,24 @@ class F(Form):
query_factory=lambda: sess.query(self.PKTest),
widget=LazySelect(),
)
d = QuerySelectField(
allow_blank=True,
blank_text="",
blank_value="",
query_factory=lambda: sess.query(self.PKTest),
get_group=lambda x: x.baz[0],
widget=LazyGroupSelect(),
)

form = F()
self.assertEqual(form.a.data, None)
self.assertEqual(
form.a(), [("1", "apple", False, {}), ("2", "banana", False, {})]
form.a(),
[
("1", "apple", False, {}),
("2", "banana", False, {}),
("3", "apricot", False, {}),
],
)
self.assertEqual(form.b.data, None)
self.assertEqual(
Expand All @@ -168,6 +200,7 @@ class F(Form):
("__None", "", True, {}),
("hello1", "apple", False, {}),
("hello2", "banana", False, {}),
("hello3", "apricot", False, {}),
],
)
self.assertEqual(form.c.data, None)
Expand All @@ -177,14 +210,32 @@ class F(Form):
("", "", True, {}),
("hello1", "apple", False, {}),
("hello2", "banana", False, {}),
("hello3", "apricot", False, {}),
],
)
self.assertEqual(form.d.data, None)
self.assertEqual(
form.d(),
[
(None, [("", "", True, {})]),
(
"a",
[("hello1", "apple", False, {}), ("hello3", "apricot", False, {})],
),
("b", [("hello2", "banana", False, {})]),
],
)
self.assertFalse(form.validate())

form = F(DummyPostData(a=["1"], b=["hello2"], c=[""]))
form = F(DummyPostData(a=["1"], b=["hello2"], c=[""], d=["hello3"]))
self.assertEqual(form.a.data.id, 1)
self.assertEqual(
form.a(), [("1", "apple", True, {}), ("2", "banana", False, {})]
form.a(),
[
("1", "apple", True, {}),
("2", "banana", False, {}),
("3", "apricot", False, {}),
],
)
self.assertEqual(form.b.data.baz, "banana")
self.assertEqual(
Expand All @@ -193,6 +244,7 @@ class F(Form):
("__None", "", False, {}),
("hello1", "apple", False, {}),
("hello2", "banana", True, {}),
("hello3", "apricot", False, {}),
],
)
self.assertEqual(form.c.data, None)
Expand All @@ -202,24 +254,43 @@ class F(Form):
("", "", True, {}),
("hello1", "apple", False, {}),
("hello2", "banana", False, {}),
("hello3", "apricot", False, {}),
],
)
self.assertEqual(form.d.data.baz, "apricot")
self.assertEqual(
form.d(),
[
(None, [("", "", False, {})]),
(
"a",
[("hello1", "apple", False, {}), ("hello3", "apricot", True, {})],
),
("b", [("hello2", "banana", False, {})]),
],
)
self.assertTrue(form.validate())

# Make sure the query is cached
sess.add(self.Test(id=3, name="meh"))
sess.add(self.Test(id=4, name="meh"))
sess.flush()
sess.commit()
self.assertEqual(
form.a(), [("1", "apple", True, {}), ("2", "banana", False, {})]
form.a(),
[
("1", "apple", True, {}),
("2", "banana", False, {}),
("3", "apricot", False, {}),
],
)
form.a._object_list = None
self.assertEqual(
form.a(),
[
("1", "apple", True, {}),
("2", "banana", False, {}),
("3", "meh", False, {}),
("3", "apricot", False, {}),
("4", "meh", False, {}),
],
)

Expand Down Expand Up @@ -264,7 +335,12 @@ def test_single_value_without_factory(self):
form.a.query = self.sess.query(self.Test)
self.assertEqual([1], [v.id for v in form.a.data])
self.assertEqual(
form.a(), [("1", "apple", True, {}), ("2", "banana", False, {})]
form.a(),
[
("1", "apple", True, {}),
("2", "banana", False, {}),
("3", "apricot", False, {}),
],
)
self.assertTrue(form.validate())

Expand All @@ -273,11 +349,16 @@ def test_multiple_values_without_query_factory(self):
form.a.query = self.sess.query(self.Test)
self.assertEqual([1, 2], [v.id for v in form.a.data])
self.assertEqual(
form.a(), [("1", "apple", True, {}), ("2", "banana", True, {})]
form.a(),
[
("1", "apple", True, {}),
("2", "banana", True, {}),
("3", "apricot", False, {}),
],
)
self.assertTrue(form.validate())

form = self.F(DummyPostData(a=["1", "3"]))
form = self.F(DummyPostData(a=["1", "4"]))
form.a.query = self.sess.query(self.Test)
self.assertEqual([x.id for x in form.a.data], [1])
self.assertFalse(form.validate())
Expand All @@ -296,7 +377,12 @@ class F(Form):
form = F()
self.assertEqual([v.id for v in form.a.data], [2])
self.assertEqual(
form.a(), [("1", "apple", False, {}), ("2", "banana", True, {})]
form.a(),
[
("1", "apple", False, {}),
("2", "banana", True, {}),
("3", "apricot", False, {}),
],
)
self.assertTrue(form.validate())

Expand Down