Merge branch 'main' of https://repo.backender.de/holger/Django-Translatable-Fields
This commit is contained in:
@@ -78,7 +78,7 @@ def translatable_context(language):
|
|||||||
with translatable_context('de'):
|
with translatable_context('de'):
|
||||||
products = Product.objects.search('moep') # Searches in German
|
products = Product.objects.search('moep') # Searches in German
|
||||||
for product in products:
|
for product in products:
|
||||||
print(product.name) # Shows German name
|
logging.debug(product.name) # Shows German name
|
||||||
"""
|
"""
|
||||||
with TranslatableContext(language):
|
with TranslatableContext(language):
|
||||||
yield
|
yield
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ Version: 0.1.0
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import logging
|
||||||
from django import forms
|
from django import forms
|
||||||
from django.core.exceptions import ValidationError
|
from django.core.exceptions import ValidationError
|
||||||
from django.utils.translation import gettext_lazy as _
|
from django.utils.translation import gettext_lazy as _
|
||||||
@@ -59,7 +60,7 @@ class TranslatableFormField(forms.CharField):
|
|||||||
|
|
||||||
if row and row[0]:
|
if row and row[0]:
|
||||||
raw_json = row[0]
|
raw_json = row[0]
|
||||||
print(f"Form field get_bound_field - got raw JSON for {field_name}: {repr(raw_json)}")
|
logging.debug(f"Form field get_bound_field - got raw JSON for {field_name}: {repr(raw_json)}")
|
||||||
|
|
||||||
# Store this for prepare_value to use
|
# Store this for prepare_value to use
|
||||||
self._raw_db_value = raw_json
|
self._raw_db_value = raw_json
|
||||||
@@ -71,11 +72,11 @@ class TranslatableFormField(forms.CharField):
|
|||||||
'raw_json': raw_json
|
'raw_json': raw_json
|
||||||
}
|
}
|
||||||
else:
|
else:
|
||||||
print(f"Form field get_bound_field - no raw data found for {field_name}")
|
logging.debug(f"Form field get_bound_field - no raw data found for {field_name}")
|
||||||
self._raw_db_value = None
|
self._raw_db_value = None
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Form field get_bound_field - DB error: {e}")
|
logging.debug(f"Form field get_bound_field - DB error: {e}")
|
||||||
self._raw_db_value = None
|
self._raw_db_value = None
|
||||||
|
|
||||||
return bound_field
|
return bound_field
|
||||||
@@ -132,17 +133,17 @@ class TranslatableFormField(forms.CharField):
|
|||||||
|
|
||||||
def prepare_value(self, value):
|
def prepare_value(self, value):
|
||||||
"""Prepare value for widget display - use raw JSON if available"""
|
"""Prepare value for widget display - use raw JSON if available"""
|
||||||
print(f"Form field prepare_value - received: {repr(value)}, type: {type(value)}")
|
logging.debug(f"Form field prepare_value - received: {repr(value)}, type: {type(value)}")
|
||||||
|
|
||||||
# Use raw DB value if we have it
|
# Use raw DB value if we have it
|
||||||
if hasattr(self, '_raw_db_value') and self._raw_db_value:
|
if hasattr(self, '_raw_db_value') and self._raw_db_value:
|
||||||
try:
|
try:
|
||||||
parsed = json.loads(self._raw_db_value)
|
parsed = json.loads(self._raw_db_value)
|
||||||
if isinstance(parsed, dict):
|
if isinstance(parsed, dict):
|
||||||
print(f"Form field prepare_value - using raw DB dict: {parsed}")
|
logging.debug(f"Form field prepare_value - using raw DB dict: {parsed}")
|
||||||
return parsed
|
return parsed
|
||||||
except (json.JSONDecodeError, ValueError):
|
except (json.JSONDecodeError, ValueError):
|
||||||
print(f"Form field prepare_value - raw DB value parse failed")
|
logging.debug(f"Form field prepare_value - raw DB value parse failed")
|
||||||
|
|
||||||
# Fallback to original logic
|
# Fallback to original logic
|
||||||
if not value:
|
if not value:
|
||||||
@@ -152,20 +153,20 @@ class TranslatableFormField(forms.CharField):
|
|||||||
try:
|
try:
|
||||||
parsed = json.loads(value)
|
parsed = json.loads(value)
|
||||||
if isinstance(parsed, dict):
|
if isinstance(parsed, dict):
|
||||||
print(f"Form field prepare_value - returning parsed dict: {parsed}")
|
logging.debug(f"Form field prepare_value - returning parsed dict: {parsed}")
|
||||||
return parsed
|
return parsed
|
||||||
except (json.JSONDecodeError, ValueError):
|
except (json.JSONDecodeError, ValueError):
|
||||||
pass
|
pass
|
||||||
result = {'en': value}
|
result = {'en': value}
|
||||||
print(f"Form field prepare_value - returning english dict: {result}")
|
logging.debug(f"Form field prepare_value - returning english dict: {result}")
|
||||||
return result
|
return result
|
||||||
|
|
||||||
if isinstance(value, dict):
|
if isinstance(value, dict):
|
||||||
print(f"Form field prepare_value - returning dict as-is: {value}")
|
logging.debug(f"Form field prepare_value - returning dict as-is: {value}")
|
||||||
return value
|
return value
|
||||||
|
|
||||||
result = {'en': str(value)}
|
result = {'en': str(value)}
|
||||||
print(f"Form field prepare_value - returning converted dict: {result}")
|
logging.debug(f"Form field prepare_value - returning converted dict: {result}")
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ Version: 0.1.0
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import logging
|
||||||
from django.db import migrations
|
from django.db import migrations
|
||||||
from django.utils.translation import get_language
|
from django.utils.translation import get_language
|
||||||
|
|
||||||
@@ -65,7 +66,7 @@ class ConvertTranslatableField(migrations.Operation):
|
|||||||
|
|
||||||
def _convert_json_to_string(self, model, schema_editor):
|
def _convert_json_to_string(self, model, schema_editor):
|
||||||
"""Convert JSON translations to single language string"""
|
"""Convert JSON translations to single language string"""
|
||||||
print(f"Converting {self.model_name}.{self.field_name} from JSON to string (language: {self.language})")
|
logging.debug(f"Converting {self.model_name}.{self.field_name} from JSON to string (language: {self.language})")
|
||||||
|
|
||||||
for obj in model.objects.all():
|
for obj in model.objects.all():
|
||||||
field_value = getattr(obj, self.field_name)
|
field_value = getattr(obj, self.field_name)
|
||||||
@@ -89,7 +90,7 @@ class ConvertTranslatableField(migrations.Operation):
|
|||||||
f"UPDATE {table_name} SET {self.field_name} = %s WHERE id = %s",
|
f"UPDATE {table_name} SET {self.field_name} = %s WHERE id = %s",
|
||||||
[new_value, obj.pk]
|
[new_value, obj.pk]
|
||||||
)
|
)
|
||||||
print(f" Converted {obj.pk}: {field_value} -> {new_value}")
|
logging.debug(f" Converted {obj.pk}: {field_value} -> {new_value}")
|
||||||
|
|
||||||
except (json.JSONDecodeError, TypeError):
|
except (json.JSONDecodeError, TypeError):
|
||||||
# Already a string, leave as-is
|
# Already a string, leave as-is
|
||||||
@@ -97,7 +98,7 @@ class ConvertTranslatableField(migrations.Operation):
|
|||||||
|
|
||||||
def _convert_string_to_json(self, model, schema_editor):
|
def _convert_string_to_json(self, model, schema_editor):
|
||||||
"""Convert single language string to JSON translations"""
|
"""Convert single language string to JSON translations"""
|
||||||
print(f"Converting {self.model_name}.{self.field_name} from string to JSON (language: {self.language})")
|
logging.debug(f"Converting {self.model_name}.{self.field_name} from string to JSON (language: {self.language})")
|
||||||
|
|
||||||
for obj in model.objects.all():
|
for obj in model.objects.all():
|
||||||
field_value = getattr(obj, self.field_name)
|
field_value = getattr(obj, self.field_name)
|
||||||
@@ -117,7 +118,7 @@ class ConvertTranslatableField(migrations.Operation):
|
|||||||
f"UPDATE {table_name} SET {self.field_name} = %s WHERE id = %s",
|
f"UPDATE {table_name} SET {self.field_name} = %s WHERE id = %s",
|
||||||
[new_value, obj.pk]
|
[new_value, obj.pk]
|
||||||
)
|
)
|
||||||
print(f" Converted {obj.pk}: {field_value} -> {new_value}")
|
logging.debug(f" Converted {obj.pk}: {field_value} -> {new_value}")
|
||||||
|
|
||||||
def describe(self):
|
def describe(self):
|
||||||
direction = "translatable" if self.to_translatable else "non-translatable"
|
direction = "translatable" if self.to_translatable else "non-translatable"
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ Version: 0.1.0
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import logging
|
||||||
from django import forms
|
from django import forms
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.utils.translation import get_language, gettext_lazy as _
|
from django.utils.translation import get_language, gettext_lazy as _
|
||||||
@@ -141,8 +142,8 @@ class TranslatableWidget(forms.Widget):
|
|||||||
if attrs is None:
|
if attrs is None:
|
||||||
attrs = {}
|
attrs = {}
|
||||||
|
|
||||||
# Debug: Print what we're getting as value
|
# Debug: logging.debug what we're getting as value
|
||||||
print(f"Widget render - name: {name}, value: {repr(value)}, type: {type(value)}")
|
logging.debug(f"Widget render - name: {name}, value: {repr(value)}, type: {type(value)}")
|
||||||
|
|
||||||
# Try to get the full translations from the current context
|
# Try to get the full translations from the current context
|
||||||
translations = {}
|
translations = {}
|
||||||
@@ -162,7 +163,7 @@ class TranslatableWidget(forms.Widget):
|
|||||||
elif value:
|
elif value:
|
||||||
translations = {'en': str(value)}
|
translations = {'en': str(value)}
|
||||||
|
|
||||||
print(f"Widget render - parsed translations from value: {translations}")
|
logging.debug(f"Widget render - parsed translations from value: {translations}")
|
||||||
|
|
||||||
# If translations are empty or only have English, try to get from the bound instance
|
# If translations are empty or only have English, try to get from the bound instance
|
||||||
if len(translations) <= 1 and hasattr(self, '_instance_data'):
|
if len(translations) <= 1 and hasattr(self, '_instance_data'):
|
||||||
@@ -183,15 +184,15 @@ class TranslatableWidget(forms.Widget):
|
|||||||
try:
|
try:
|
||||||
db_translations = json.loads(row[0])
|
db_translations = json.loads(row[0])
|
||||||
if isinstance(db_translations, dict):
|
if isinstance(db_translations, dict):
|
||||||
print(f"Widget render - got translations for instance {instance.pk}: {db_translations}")
|
logging.debug(f"Widget render - got translations for instance {instance.pk}: {db_translations}")
|
||||||
translations = db_translations
|
translations = db_translations
|
||||||
except (json.JSONDecodeError, TypeError):
|
except (json.JSONDecodeError, TypeError):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Widget render - instance DB lookup error: {e}")
|
logging.debug(f"Widget render - instance DB lookup error: {e}")
|
||||||
|
|
||||||
print(f"Widget render - final translations: {translations}")
|
logging.debug(f"Widget render - final translations: {translations}")
|
||||||
|
|
||||||
|
|
||||||
# Get English value for primary field
|
# Get English value for primary field
|
||||||
|
|||||||
Reference in New Issue
Block a user