Commits

Luke Plant  committed faaf05a

Fixed crash when invalid foreign key values are in query string

  • Participants
  • Parent commits 196e4ac

Comments (0)

Files changed (2)

File django_easyfilters/filters.py

     """
     Filter for ForeignKey fields.
     """
-    def __init__(self, *args, **kwargs):
-        super(ForeignKeyFilter, self).__init__(*args, **kwargs)
+    def __init__(self, field, model, params, **kwargs):
+        self.field_obj = model._meta.get_field(field)
         self.rel_model = self.field_obj.rel.to
         self.rel_field = self.field_obj.rel.get_related_field()
+        super(ForeignKeyFilter, self).__init__(field, model, params, **kwargs)
+
+    def choice_from_param(self, param):
+        try:
+            return self.rel_field.to_python(param)
+        except ValidationError:
+            raise ValueError()
 
     def display_choice(self, choice):
         lookup = {self.rel_field.name: choice}

File django_easyfilters/tests/filterset.py

         qs_reverted = filter3.apply_filter(qs)
         self.assertEqual(qs, qs_reverted)
 
+    def test_foreignkey_invalid_query(self):
+        self.do_invalid_query_param_test(lambda params:
+                                             ForeignKeyFilter('genre', Book, params),
+                                         MultiValueDict({'genre':['xxx']}))
+
     def test_values_filter(self):
         """
         Tests for ValuesFilter