diff --git a/modeltranslation/fields.py b/modeltranslation/fields.py index b873edc..91e0f69 100644 --- a/modeltranslation/fields.py +++ b/modeltranslation/fields.py @@ -156,7 +156,7 @@ class TranslationFieldDescriptor(object): # Here we check only for None and '', because e.g. 0 should not fall back. if val is not None and val != '': return val - if self.fallback_value is None: + if self.fallback_value is None or not mt_settings.ENABLE_FALLBACKS: return self.field.get_default() else: return self.fallback_value diff --git a/modeltranslation/settings.py b/modeltranslation/settings.py index 19937a2..1a92c77 100644 --- a/modeltranslation/settings.py +++ b/modeltranslation/settings.py @@ -51,3 +51,4 @@ for key, value in FALLBACK_LANGUAGES.iteritems(): if lang not in AVAILABLE_LANGUAGES: raise ImproperlyConfigured( 'MODELTRANSLATION_FALLBACK_LANGUAGES: "%s" not in LANGUAGES setting.' % lang) +ENABLE_FALLBACKS = getattr(settings, 'MODELTRANSLATION_ENABLE_FALLBACKS', True) diff --git a/modeltranslation/utils.py b/modeltranslation/utils.py index d3049a4..27eb9b1 100644 --- a/modeltranslation/utils.py +++ b/modeltranslation/utils.py @@ -90,6 +90,8 @@ def resolution_order(lang, override=None): First is always the parameter language, later are fallback languages. Override parameter has priority over FALLBACK_LANGUAGES. """ + if not settings.ENABLE_FALLBACKS: + return (lang,) if override is None: override = {} fallback_for_lang = override.get(lang, settings.FALLBACK_LANGUAGES.get(lang, ())) @@ -123,3 +125,25 @@ def auto_populate(mode='all'): yield finally: settings.AUTO_POPULATE = current_population_mode + + +@contextmanager +def fallbacks(enable=True): + """ + Temporarily switch all language fallbacks on or off. + + Example: + + with fallbacks(False): + lang_has_slug = bool(self.slug) + + May be used to enable fallbacks just when they're needed saving on some + processing or check if there is a value for the current language (not + knowing the language) + """ + current_enable_fallbacks = settings.ENABLE_FALLBACKS + settings.ENABLE_FALLBACKS = enable + try: + yield + finally: + settings.ENABLE_FALLBACKS = current_enable_fallbacks