Skip to content

Commit

Permalink
fix: Preserve blank value for optional fields
Browse files Browse the repository at this point in the history
  • Loading branch information
last-partizan committed Dec 26, 2024
1 parent 1b0bf21 commit f197adc
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
11 changes: 8 additions & 3 deletions modeltranslation/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,17 +139,22 @@ def __init__(
# TODO: Do we really want to enforce null *at all*? Shouldn't this
# better honour the null setting of the translated field?
self.null = True

# We preserve original blank value for translated fields,
# when they're in 'required_languages'.
# So they will be only required if original field itself was required.
original_blank = self.blank
self.blank = True

# Take required_languages translation option into account
# Take required_languages translation option into account.
trans_opts = translator.get_options_for_model(self.model)
if trans_opts.required_languages:
required_languages = trans_opts.required_languages
if isinstance(required_languages, (tuple, list)):
# All fields
if self.language in required_languages:
# self.null = False
self.blank = False
self.blank = original_blank
else:
# Certain fields only
# Try current language - if not present, try 'default' key
Expand All @@ -161,7 +166,7 @@ def __init__(
# TODO: We might have to handle the whole thing through the
# FieldsAggregationMetaClass, as fields can be inherited.
# self.null = False
self.blank = False
self.blank = original_blank

# Adjust the name of this field to reflect the language
self.attname = build_localized_fieldname(self.translated_field.name, language)
Expand Down
3 changes: 3 additions & 0 deletions modeltranslation/tests/translation.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,9 @@ class RequiredTranslationOptions(TranslationOptions):
fields = ("non_req", "req", "req_reg", "req_en_reg")
required_languages = {
"en": (
# We include `non_req` field here, to test that it's `blank` attribute is preserved,
# even when languages is required.
"non_req",
"req_reg",
"req_en_reg",
),
Expand Down

0 comments on commit f197adc

Please sign in to comment.