Skip to content

Commit

Permalink
Fix for verbose_field_name (#722)
Browse files Browse the repository at this point in the history
* Failing test for #716

* Handle case where related_name is None
  • Loading branch information
Carlton Gibson authored May 19, 2017
1 parent 876d79f commit 9564293
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 7 deletions.
5 changes: 4 additions & 1 deletion django_filters/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,10 @@ def verbose_field_name(model, field_name):
names = []
for part in parts:
if isinstance(part, ForeignObjectRel):
names.append(part.related_name.replace('_', ' '))
if part.related_name:
names.append(part.related_name.replace('_', ' '))
else:
return '[invalid name]'
else:
names.append(force_text(part.verbose_name))

Expand Down
36 changes: 30 additions & 6 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,16 @@
verbose_field_name, verbose_lookup_expr, label_for_filter, raw_validation,
)

from .models import User
from .models import Article
from .models import Book
from .models import HiredWorker
from .models import Business
from .models import NetworkSetting
from .models import (
User,
Article,
Book,
HiredWorker,
Business,
NetworkSetting,
Company,
Account,
)


class GetFieldPartsTests(TestCase):
Expand Down Expand Up @@ -253,6 +257,26 @@ def test_lazy_text(self):
verbose_name = verbose_field_name(User, 'username')
self.assertEqual(verbose_name, 'username')

def test_forwards_fk(self):
verbose_name = verbose_field_name(Article, 'author')
self.assertEqual(verbose_name, 'author')

def test_backwards_fk(self):
# https://github.com/carltongibson/django-filter/issues/716

# related_name is set
verbose_name = verbose_field_name(Company, 'locations')
self.assertEqual(verbose_name, 'locations')

# related_name not set. Auto-generated relation is `article_set`
# _meta.get_field raises FieldDoesNotExist
verbose_name = verbose_field_name(User, 'article_set')
self.assertEqual(verbose_name, '[invalid name]')

# WRONG NAME! Returns ManyToOneRel with related_name == None.
verbose_name = verbose_field_name(User, 'article')
self.assertEqual(verbose_name, '[invalid name]')


class VerboseLookupExprTests(TestCase):

Expand Down

0 comments on commit 9564293

Please sign in to comment.