From 28c06040ff5fe03547099acbce18bef81f45277e Mon Sep 17 00:00:00 2001 From: Andy Chosak Date: Mon, 2 Jul 2018 11:02:10 -0400 Subject: [PATCH] alphabetically order blocks in search form This commit explicitly orders blocks alphabetically in the Wagtail admin search form. Previously the ordering was unspecified and so was arbitrarily ordered depending on the database backend. Fixes #12. --- wagtailinventory/forms.py | 10 ++++--- wagtailinventory/tests/test_forms.py | 41 ++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 4 deletions(-) create mode 100644 wagtailinventory/tests/test_forms.py diff --git a/wagtailinventory/forms.py b/wagtailinventory/forms.py index 1415745..d48f97a 100644 --- a/wagtailinventory/forms.py +++ b/wagtailinventory/forms.py @@ -31,10 +31,12 @@ class PageBlockQueryForm(forms.Form): def __init__(self, *args, **kwargs): super(PageBlockQueryForm, self).__init__(*args, **kwargs) - block_choices = BLANK_CHOICE_DASH + [ - (b, b) for b in - PageBlock.objects.values_list('block', flat=True).distinct() - ] + blocks = PageBlock.objects \ + .values_list('block', flat=True) \ + .distinct() \ + .order_by('block') + + block_choices = BLANK_CHOICE_DASH + [(b, b) for b in blocks] self.fields['block'].choices = block_choices diff --git a/wagtailinventory/tests/test_forms.py b/wagtailinventory/tests/test_forms.py new file mode 100644 index 0000000..6bc91c5 --- /dev/null +++ b/wagtailinventory/tests/test_forms.py @@ -0,0 +1,41 @@ +from __future__ import absolute_import, unicode_literals + +from django.db.models.fields import BLANK_CHOICE_DASH +from django.test import TestCase + +try: + from wagtail.core.models import Page, Site +except ImportError: # pragma: no cover; fallback for Wagtail <2.0 + from wagtail.wagtailcore.models import Page, Site + +from wagtailinventory.forms import PageBlockQueryForm +from wagtailinventory.models import PageBlock + + +class TestPageBlockQueryForm(TestCase): + def test_no_page_blocks_in_database_form_has_blank_choice(self): + form = PageBlockQueryForm() + form_choices = form.fields['block'].choices + + self.assertEqual(len(form_choices), 1) + self.assertEqual(form_choices, BLANK_CHOICE_DASH) + + def test_form_choices_alphabetized(self): + root_page = Site.objects.get(is_default_site=True).root_page + page = Page(title='Title', slug='title') + root_page.add_child(instance=page) + + for block in ( + 'blocks.mango', + 'blocks.apple', + 'blocks.banana', + ): + PageBlock.objects.create(page=page, block=block) + + form = PageBlockQueryForm() + form_choices = form.fields['block'].choices + + self.assertEqual(len(form_choices), 4) + self.assertEqual(form_choices[1][0], 'blocks.apple') + self.assertEqual(form_choices[2][0], 'blocks.banana') + self.assertEqual(form_choices[3][0], 'blocks.mango')