Skip to content

Commit

Permalink
Handle invalid AutoFilter field names (#345)
Browse files Browse the repository at this point in the history
  • Loading branch information
rpkilby authored Aug 8, 2020
1 parent f067fd3 commit 5ad0de6
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
6 changes: 5 additions & 1 deletion rest_framework_filters/filterset.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,11 @@ def get_fields(cls):
for name, lookups in fields.items():
if lookups == filters.ALL_LOOKUPS:
field = get_model_field(cls._meta.model, name)
fields[name] = utils.lookups_for_field(field)
if field is not None:
fields[name] = utils.lookups_for_field(field)
else:
# FilterSet will handle invalid name
fields[name] = []

return fields

Expand Down
24 changes: 24 additions & 0 deletions tests/test_filterset.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import sys
import unittest
import warnings

import django_filters
from django.test import TestCase
from django_filters.filters import BaseInFilter
from rest_framework.test import APIRequestFactory
Expand Down Expand Up @@ -134,6 +136,28 @@ class Meta:
'pk': filters.NumberFilter,
})

@unittest.skipIf(django_filters.VERSION < (2, 2), 'requires django-filter 2.2')
def test_autofilter_invalid_field(self):
msg = "'Meta.fields' must not contain non-model field names: xyz"
with self.assertRaisesMessage(TypeError, msg):
class F(FilterSet):
pk = filters.AutoFilter(field_name='xyz', lookups=['exact'])

class Meta:
model = Note
fields = []

@unittest.skipIf(django_filters.VERSION < (2, 2), 'requires django-filter 2.2')
def test_all_lookups_invalid_field(self):
msg = "'Meta.fields' must not contain non-model field names: xyz"
with self.assertRaisesMessage(TypeError, msg):
class F(FilterSet):
class Meta:
model = Note
fields = {
'xyz': '__all__',
}

def test_relatedfilter_doesnt_expand_declared(self):
# See: https://github.com/philipn/django-rest-framework-filters/issues/234
class F(FilterSet):
Expand Down

0 comments on commit 5ad0de6

Please sign in to comment.