|
7 | 7 | from garnett.utils import get_languages, get_current_language |
8 | 8 |
|
9 | 9 |
|
| 10 | +RANDOM_STR = "f6e56ce9-cc87-45ac-8a19-8c34136e6f52" |
| 11 | +BLEACH_STR = "string to be replace" |
| 12 | + |
| 13 | + |
| 14 | +class CustomTestingField(models.TextField): |
| 15 | + def get_db_prep_save(self, value, connection): |
| 16 | + """ |
| 17 | + Note: If there is data migration when migrating to TranslatedField, the manually added |
| 18 | + step_1_safe_encode_content() function in the migration file will base64 encode the value in the field |
| 19 | + before get_db_prep_save is called. |
| 20 | +
|
| 21 | + For example: |
| 22 | + old value = "this is a book" |
| 23 | + new value = '{"en": "dGhpcyBpcyBhIGJvb2s="}' |
| 24 | +
|
| 25 | + The new value is then parse to the get_db_prep_save() function. |
| 26 | + If custom get_db_prep_save() function is used you will need to make sure that the custom get_db_prep_save() function is |
| 27 | + not modifying the input value. |
| 28 | +
|
| 29 | + Some examples, |
| 30 | + 1. if the custom get_db_prep_save() function append a fix str to all input value: |
| 31 | + input value = '{"en": "dGhpcyBpcyBhIGJvb2s="}' |
| 32 | + return value = '{"en": "dGhpcyBpcyBhIGJvb2s="}1234567' |
| 33 | + this would raise "django.db.utils.DataError: invalid input syntax for type json" because the return value |
| 34 | + from the custom get_db_prep_save() function is not valid json |
| 35 | +
|
| 36 | + 2. if the custom get_db_prep_save() function bleach certain substring (e.g dGhpcy) on the input value: |
| 37 | + input value = '{"en": "dGhpcyBpcyBhIGJvb2s="}' |
| 38 | + return value = '{"en": "BpcyBhIGJvb2s="}' |
| 39 | + this would modify the base64 value and decoding the modfied base64 value would return unexpected result |
| 40 | + """ |
| 41 | + if value is None: |
| 42 | + return super().get_db_prep_save(value, connection) |
| 43 | + bleached_value = value.replace(BLEACH_STR, RANDOM_STR) |
| 44 | + return super().get_db_prep_save(bleached_value, connection) |
| 45 | + |
| 46 | + |
10 | 47 | def validate_length(value): |
11 | 48 | if len(value) < 3: |
12 | 49 | raise ValidationError(_("Title is too short")) |
@@ -70,6 +107,8 @@ class Book(models.Model): |
70 | 107 |
|
71 | 108 | category = models.JSONField(blank=True, null=True) |
72 | 109 |
|
| 110 | + other_info = fields.Translated(CustomTestingField(blank=True, default="")) |
| 111 | + |
73 | 112 | def get_absolute_url(self): |
74 | 113 | return f"/book/{self.pk}" |
75 | 114 |
|
|
0 commit comments