Skip to content

Commit

Permalink
Merge pull request #54 from maykinmedia/53-handle-localized-defaults-…
Browse files Browse the repository at this point in the history
…in-example-generator

🐛 Handle gettext wrapped default values in example generator
  • Loading branch information
stevenbal authored Jan 23, 2025
2 parents d7d4fe8 + a35cd99 commit 700c281
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 5 deletions.
17 changes: 12 additions & 5 deletions django_setup_configuration/documentation/setup_config_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
get_origin,
)

from django.utils.functional import Promise

import ruamel.yaml
from docutils import nodes
from docutils.parsers.rst import Directive
Expand Down Expand Up @@ -68,11 +70,16 @@ def _get_default_from_field_info(field_info: FieldInfo) -> Any:
"""
if field_info.default_factory:
return field_info.default_factory()
return (
field_info.default.value
if isinstance(field_info.default, Enum)
else field_info.default
)

match field_info.default:
case Promise():
# Effectively a callable -- call the lazy function, e.g. gettext(), so we're
# left with a simple value, not a complex object which is hard to serialize
return field_info.default._proxy____cast()
case Enum():
return field_info.default.value
case _:
return field_info.default


def _yaml_set_wrapped_comment(
Expand Down
6 changes: 6 additions & 0 deletions testapp/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from django.contrib.postgres.fields import ArrayField
from django.db import models
from django.utils.functional import lazy
from django.utils.translation import gettext_lazy as _


class StrChoices(models.TextChoices):
Expand Down Expand Up @@ -60,3 +62,7 @@ class DjangoModel(models.Model):
models.JSONField(), default=lambda: [{"foo": "bar"}, {"foo": "baz"}]
)
array_field = ArrayField(models.JSONField(), null=True, blank=True)
str_with_localized_default = models.TextField(default=_("Localized default"))
int_with_lazy_default = models.IntegerField(
default=lazy(lambda: 42, int)(), verbose_name="int with lazy default"
)
10 changes: 10 additions & 0 deletions tests/test_documentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ class Meta:
"json_with_default_factory",
"nullable_str",
"int_with_choices_and_blank_and_non_choice_default",
"str_with_localized_default",
"int_with_lazy_default",
)
}
extra_kwargs = {
Expand Down Expand Up @@ -259,6 +261,14 @@ def test_directive_output(register_directive, docutils_document):
# DEFAULT VALUE: 42
# REQUIRED: false
int_with_choices_and_blank_and_non_choice_default: 42
# DEFAULT VALUE: "Localized default"
# REQUIRED: false
str_with_localized_default: Localized default
# DEFAULT VALUE: 42
# REQUIRED: false
int_with_lazy_default: 42
"""
)

Expand Down

0 comments on commit 700c281

Please sign in to comment.