Skip to content

Commit

Permalink
Make lookup required when value is provided
Browse files Browse the repository at this point in the history
  • Loading branch information
Ryan P Kilby committed May 21, 2018
1 parent 26dbb81 commit b1c359a
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
13 changes: 11 additions & 2 deletions django_filters/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,10 @@ def __new__(cls, value, lookup_expr):


class LookupChoiceField(forms.MultiValueField):
default_error_messages = {
'lookup_required': _('Select a lookup.'),
}

def __init__(self, field, lookup_choices, *args, **kwargs):
empty_label = kwargs.pop('empty_label', settings.EMPTY_CHOICE_LABEL)
fields = (field, ChoiceField(choices=lookup_choices, empty_label=empty_label))
Expand All @@ -103,8 +107,13 @@ def __init__(self, field, lookup_choices, *args, **kwargs):
def compress(self, data_list):
if len(data_list) == 2:
value, lookup_expr = data_list
if value not in EMPTY_VALUES and lookup_expr not in EMPTY_VALUES:
return Lookup(value=value, lookup_expr=lookup_expr)
if value not in EMPTY_VALUES:
if lookup_expr not in EMPTY_VALUES:
return Lookup(value=value, lookup_expr=lookup_expr)
else:
raise forms.ValidationError(
self.error_messages['lookup_required'],
code='lookup_required')
return None


Expand Down
3 changes: 3 additions & 0 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,9 @@ def test_clean(self):
f.clean([]),
None)

with self.assertRaisesMessage(forms.ValidationError, 'Select a lookup.'):
f.clean(['12.34', ''])

def test_render_used_html5(self):
inner = forms.DecimalField()
f = LookupChoiceField(inner, [('gt', 'gt'), ('lt', 'lt')], empty_label=None)
Expand Down
9 changes: 9 additions & 0 deletions tests/test_filtering.py
Original file line number Diff line number Diff line change
Expand Up @@ -1644,10 +1644,12 @@ def test_filtering(self):
f = F({'price': '15', 'price_lookup': 'lt'})
self.assertQuerysetEqual(f.qs, ['Ender\'s Game'], lambda o: o.title)
f = F({'price': '', 'price_lookup': 'lt'})
self.assertTrue(f.is_valid())
self.assertQuerysetEqual(f.qs,
['Ender\'s Game', 'Rainbow Six', 'Snowcrash'],
lambda o: o.title, ordered=False)
f = F({'price': '15'})
self.assertFalse(f.is_valid())
self.assertQuerysetEqual(f.qs,
['Ender\'s Game', 'Rainbow Six', 'Snowcrash'],
lambda o: o.title, ordered=False)
Expand All @@ -1666,6 +1668,13 @@ def test_lookup_choices_validation(self):
'price': ['Select a valid choice. asdf is not one of the available choices.'],
})

def test_lookup_omitted(self):
f = self.BookFilter({'price': '1'})
self.assertFalse(f.is_valid())
self.assertEqual(f.errors, {
'price': ['Select a lookup.'],
})


# use naive datetimes, as pytz is required to perform
# date lookups when timezones are involved.
Expand Down

0 comments on commit b1c359a

Please sign in to comment.