|
1
|
1 |
|
from django.conf import settings |
|
2
|
1 |
|
from django.utils.text import slugify |
|
3
|
|
|
|
|
4
|
1 |
|
from ..localized_value import LocalizedValue |
|
5
|
1 |
|
from .localized_autoslug_field import LocalizedAutoSlugField |
|
6
|
1 |
|
from ..util import get_language_codes |
|
7
|
|
|
|
|
8
|
|
|
|
|
9
|
1 |
|
class LocalizedUniqueSlugField(LocalizedAutoSlugField): |
|
10
|
|
|
"""Automatically provides slugs for a localized |
|
11
|
|
|
field upon saving." |
|
12
|
|
|
|
|
13
|
|
|
An improved version of :see:LocalizedAutoSlugField, |
|
14
|
|
|
which adds: |
|
15
|
|
|
|
|
16
|
|
|
- Concurrency safety |
|
17
|
|
|
- Improved performance |
|
18
|
|
|
|
|
19
|
|
|
When in doubt, use this over :see:LocalizedAutoSlugField. |
|
20
|
|
|
""" |
|
21
|
|
|
|
|
22
|
1 |
|
def __init__(self, *args, **kwargs): |
|
23
|
|
|
"""Initializes a new instance of :see:LocalizedUniqueSlugField.""" |
|
24
|
|
|
|
|
25
|
1 |
|
self.populate_from = kwargs.pop('populate_from') |
|
26
|
1 |
|
kwargs['uniqueness'] = kwargs.pop('uniqueness', get_language_codes()) |
|
27
|
|
|
|
|
28
|
1 |
|
super(LocalizedAutoSlugField, self).__init__( |
|
|
|
|
|
|
29
|
|
|
*args, |
|
30
|
|
|
**kwargs |
|
31
|
|
|
) |
|
32
|
|
|
|
|
33
|
1 |
|
def pre_save(self, instance, add: bool): |
|
34
|
|
|
"""Ran just before the model is saved, allows us to built |
|
35
|
|
|
the slug. |
|
36
|
|
|
|
|
37
|
|
|
Arguments: |
|
38
|
|
|
instance: |
|
39
|
|
|
The model that is being saved. |
|
40
|
|
|
|
|
41
|
|
|
add: |
|
42
|
|
|
Indicates whether this is a new entry |
|
43
|
|
|
to the database or an update. |
|
44
|
|
|
|
|
45
|
|
|
Returns: |
|
46
|
|
|
The localized slug that was generated. |
|
47
|
|
|
""" |
|
48
|
|
|
|
|
49
|
1 |
|
slugs = LocalizedValue() |
|
50
|
|
|
|
|
51
|
1 |
|
for lang_code, _ in settings.LANGUAGES: |
|
52
|
1 |
|
value = self._get_populate_from_value( |
|
53
|
|
|
instance, |
|
54
|
|
|
self.populate_from, |
|
55
|
|
|
lang_code |
|
56
|
|
|
) |
|
57
|
|
|
|
|
58
|
1 |
|
if not value: |
|
59
|
1 |
|
continue |
|
60
|
|
|
|
|
61
|
1 |
|
slug = slugify(value, allow_unicode=True) |
|
62
|
1 |
|
if instance.retries > 0: |
|
63
|
1 |
|
slug += '-%d' % instance.retries |
|
64
|
|
|
|
|
65
|
1 |
|
slugs.set(lang_code, slug) |
|
66
|
|
|
|
|
67
|
1 |
|
setattr(instance, self.name, slugs) |
|
68
|
|
|
return slugs |
|
69
|
|
|
|