Skip to content

Commit

Permalink
Fixup and simplify. Migrations working.
Browse files Browse the repository at this point in the history
  • Loading branch information
dokterbob authored and bikeshedder committed Dec 10, 2024
1 parent db0dfc2 commit 7b39163
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 17 deletions.
18 changes: 8 additions & 10 deletions composite_field/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,16 +66,14 @@ def contribute_to_class(self, cls, name):
self.prefix = '%s_' % name
for subfield_name, subfield in self.subfields.items():
subfield_name = self.prefix + subfield_name
verbose_name = subfield.verbose_name

# If verbose_name is a callable with a single positional
# argument or with a parent_verbose_name keyword parameter,
# call it with self.verbose_name and update it.
if callable(subfield.verbose_name):
try:
subfield.verbose_name = verbose_name(self.verbose_name)
except TypeError:
pass

if subfield.verbose_name:
# If subfields have a verbose_name set, attempt substitution
# of parent_verbose_name.

subfield.verbose_name = subfield.verbose_name % {
"parent_verbose_name": self.verbose_name
}

subfield.contribute_to_class(cls, subfield_name)
setattr(cls, name, property(self.get, self.set))
Expand Down
2 changes: 1 addition & 1 deletion composite_field_test/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
class CoordField(CompositeField):
x = models.FloatField(null=True)
y = models.FloatField(
null=True, verbose_name=lambda parent_verbose_name: f"{parent_verbose_name} yyy"
null=True, verbose_name="%(parent_verbose_name)s yyy"
)

class Proxy(CompositeField.Proxy):
Expand Down
10 changes: 4 additions & 6 deletions docs/source/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -91,20 +91,18 @@ return a custom type. A good example for this is the included
``ComplexField`` which stores a ``complex`` number in two
integer fields.

When the ``verbose_name`` on a subfield is callable, it will be called
with the parent field's ``verbose_name`` so that it can be dynamically set:
When the ``verbose_name`` is set on a subfield, ``parent_verbose_name``
will be substituted with the (default) verbose name from the parent field.

.. code-block:: python
class IntegerEstimatedRange(CompositeField):
minimum = models.DurationField(
lambda n: _("%(parent_verbose_name)s minimum") % {
"parent_verbose_name": n
}
verbose_name=_("%(parent_verbose_name)s minimum")
)
class Species(models.Model):
height = IntegerEstimatedRange(verbose_name=_("plant height"))
height = IntegerEstimatedRange(verbose_name="plant height")
This will render the verbose name as 'plant height minimum'. Translations
and internationalisation will function as expected (e.g. in some locales
Expand Down

0 comments on commit 7b39163

Please sign in to comment.