Skip to content

Commit

Permalink
Prevent REST's TranslatableModelMixin from creating instances without…
Browse files Browse the repository at this point in the history
… translation. Fixes #322.
  • Loading branch information
spectras committed Apr 28, 2017
1 parent 9d247c2 commit 0bb3859
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 1 deletion.
4 changes: 4 additions & 0 deletions docs/public/release_notes.rst
Expand Up @@ -58,6 +58,10 @@ Fixes:
- Attempting to use a reserved name for a translated field now raises an
:exc:`~django.core.exceptions.ImproperlyConfigured` exception instead of silently
ignoring the field.
- Instances created by serializers using
:class:`~hvad.contrib.restframework.serializers.TranslatableModelMixin`
in normal, non-*enforcing* mode can no longer be created without a translation.
:issue:`322`.

*****************************
1.7.0 - current release
Expand Down
8 changes: 8 additions & 0 deletions hvad/contrib/restframework/serializers.py
Expand Up @@ -238,6 +238,14 @@ def validate(self, data):
data['language_code'] = self.language
return data

def create(self, validated_data):
# Having a language_code key forces creation of a translation in default
# language, even if no translated field is provided.
# This ensures the serializer will not create untranslated instances.
if 'language_code' not in validated_data:
validated_data['language_code'] = None
return super(TranslatableModelMixin, self).create(validated_data)

def update(self, instance, data):
'Handle switching to correct translation before actual update'
enforce = 'language_code' in data
Expand Down
2 changes: 1 addition & 1 deletion hvad/test_utils/project/app/models.py
Expand Up @@ -12,7 +12,7 @@
class Normal(TranslatableModel):
shared_field = models.CharField(max_length=255)
translations = TranslatedFields(
translated_field = models.CharField(max_length=255)
translated_field = models.CharField(max_length=255, blank=True)
)

def __str__(self):
Expand Down
14 changes: 14 additions & 0 deletions hvad/tests/contrib/restframework.py
Expand Up @@ -154,6 +154,20 @@ def test_create_normal(self):
self.assertIsNotNone(obj.pk)
self.assertSavedObject(obj, 'en', **data)

def test_create_normal_no_language(self):
'Deserialize a new instance, without including any translated field'
data = {
'shared_field': 'shared',
}
serializer = AutoSerializer(data=data)
self.assertTrue(serializer.is_valid())

with translation.override('en'):
obj = serializer.save()
self.assertIsNotNone(obj.pk)
self.assertSavedObject(obj, 'en', **data)
self.assertEqual(obj.language_code, 'en')

def test_create_enforce(self):
'Deserialize a new instance, with language-enforcing mode'
data = {
Expand Down

0 comments on commit 0bb3859

Please sign in to comment.