Skip to content

Commit

Permalink
Merge pull request #13 from chosak/form-order-blocks
Browse files Browse the repository at this point in the history
Alphabetically order blocks in search form
  • Loading branch information
chosak authored Jul 10, 2018
2 parents a2f3b52 + 28c0604 commit f3d95ae
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 4 deletions.
10 changes: 6 additions & 4 deletions wagtailinventory/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
41 changes: 41 additions & 0 deletions wagtailinventory/tests/test_forms.py
Original file line number Diff line number Diff line change
@@ -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')

0 comments on commit f3d95ae

Please sign in to comment.