Skip to content

Commit

Permalink
Add support for to_field_name to SortedMultipleChoiceField
Browse files Browse the repository at this point in the history
  • Loading branch information
Conrad Kramer committed Apr 25, 2016
1 parent 185f59c commit 428a8a8
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
11 changes: 4 additions & 7 deletions sortedm2m/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,13 +105,10 @@ class SortedMultipleChoiceField(forms.ModelMultipleChoiceField):
widget = SortedCheckboxSelectMultiple

def clean(self, value):
queryset = super(SortedMultipleChoiceField, self).clean(value)
if value is None or not isinstance(queryset, QuerySet):

This comment has been minimized.

Copy link
@czpython

czpython May 25, 2016

The check for None is removed.
Throws an error when trying to iterate.

return queryset
object_list = dict((
(str_(key), value)
for key, value in iteritems(queryset.in_bulk(value))))
return [object_list[str_(pk)] for pk in value]
queryset = super(SortedMultipleChoiceField, self).clean(value)
key = self.to_field_name or 'pk'
objects = dict((force_text(getattr(o, key)), o) for o in queryset)
return [objects[force_text(val)] for val in value]

if django.VERSION < (1, 8):
def _has_changed(self, initial, data):
Expand Down
18 changes: 18 additions & 0 deletions sortedm2m_tests/test_forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ class SortedForm(forms.Form):
required=False)


class SortedNameForm(forms.Form):
values = SortedMultipleChoiceField(
queryset=Book.objects.all(),
to_field_name='name')


class TestSortedFormField(TestCase):
def setUp(self):
self.books = [Book.objects.create(name=c) for c in 'abcdefghik']
Expand All @@ -39,6 +45,18 @@ def test_sorted_field_input(self):
self.assertTrue(form.is_valid())
self.assertEqual(list(form.cleaned_data['values']), self.books[::-1])

def test_sorted_field_input_with_field_name(self):
form = SortedNameForm({'values': ['d', 'b', 'i']})
self.assertTrue(form.is_valid())
self.assertEqual(list(form.cleaned_data['values']), [
self.books[3],
self.books[1],
self.books[8]])

form = SortedNameForm({'values': [book.name for book in self.books[::-1]]})
self.assertTrue(form.is_valid())
self.assertEqual(list(form.cleaned_data['values']), self.books[::-1])

def test_form_field_on_model_field(self):
class ShelfForm(forms.ModelForm):
class Meta:
Expand Down

0 comments on commit 428a8a8

Please sign in to comment.