|
1
|
1 |
|
from django.db import models, transaction |
|
2
|
1 |
|
from django.db.utils import IntegrityError |
|
3
|
1 |
|
from django.conf import settings |
|
4
|
|
|
|
|
5
|
1 |
|
from .fields import LocalizedField |
|
6
|
1 |
|
from .localized_value import LocalizedValue |
|
7
|
|
|
|
|
8
|
|
|
|
|
9
|
1 |
|
class LocalizedModel(models.Model): |
|
10
|
|
|
"""A model that contains localized fields.""" |
|
11
|
|
|
|
|
12
|
1 |
|
class Meta: |
|
13
|
1 |
|
abstract = True |
|
14
|
|
|
|
|
15
|
1 |
|
def __init__(self, *args, **kwargs): |
|
16
|
|
|
"""Initializes a new instance of :see:LocalizedModel. |
|
17
|
|
|
|
|
18
|
|
|
Here we set all the fields that are of :see:LocalizedField |
|
19
|
|
|
to an instance of :see:LocalizedValue in case they are none |
|
20
|
|
|
so that the user doesn't explicitely have to do so.""" |
|
21
|
|
|
|
|
22
|
1 |
|
super(LocalizedModel, self).__init__(*args, **kwargs) |
|
23
|
|
|
|
|
24
|
1 |
|
for field in self._meta.get_fields(): |
|
25
|
1 |
|
if not isinstance(field, LocalizedField): |
|
26
|
1 |
|
continue |
|
27
|
|
|
|
|
28
|
1 |
|
value = getattr(self, field.name, None) |
|
29
|
|
|
|
|
30
|
1 |
|
if not isinstance(value, LocalizedValue): |
|
31
|
1 |
|
if isinstance(value, dict): |
|
32
|
1 |
|
value = LocalizedValue(value) |
|
33
|
|
|
else: |
|
34
|
1 |
|
value = LocalizedValue() |
|
35
|
|
|
|
|
36
|
1 |
|
setattr(self, field.name, value) |
|
37
|
|
|
|
|
38
|
1 |
|
def save(self, *args, **kwargs): |
|
39
|
|
|
"""Saves this model instance to the database.""" |
|
40
|
|
|
|
|
41
|
1 |
|
max_retries = getattr( |
|
42
|
|
|
settings, |
|
43
|
|
|
'LOCALIZED_FIELDS_MAX_RETRIES', |
|
44
|
|
|
100 |
|
45
|
|
|
) |
|
46
|
|
|
|
|
47
|
1 |
|
if not hasattr(self, 'retries'): |
|
48
|
1 |
|
self.retries = 0 |
|
|
|
|
|
|
49
|
|
|
|
|
50
|
1 |
|
with transaction.atomic(): |
|
51
|
1 |
|
try: |
|
52
|
1 |
|
return super(LocalizedModel, self).save(*args, **kwargs) |
|
53
|
1 |
|
except IntegrityError as ex: |
|
54
|
|
|
# this is as retarded as it looks, there's no |
|
55
|
|
|
# way we can put the retry logic inside the slug |
|
56
|
|
|
# field class... we can also not only catch exceptions |
|
57
|
|
|
# that apply to slug fields... so yea.. this is as |
|
58
|
|
|
# retarded as it gets... i am sorry :( |
|
59
|
1 |
|
if 'slug' in str(ex): |
|
60
|
1 |
|
if self.retries >= max_retries: |
|
61
|
1 |
|
raise ex |
|
62
|
|
|
|
|
63
|
1 |
|
self.retries += 1 |
|
64
|
|
|
return self.save() |
|
65
|
|
|
|
It is generally a good practice to initialize all attributes to default values in the
__init__method: