Passed
Push — master ( 759d03...5db877 )
by Swen
01:43
created

LocalizedUniqueSlugField.pre_save()   B

Complexity

Conditions 4

Size

Total Lines 36

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
c 1
b 0
f 0
dl 0
loc 36
ccs 12
cts 12
cp 1
crap 4
rs 8.5806
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__(
0 ignored issues
show
Bug introduced by
The first argument passed to super() should be the super-class name, but LocalizedAutoSlugField was given.
Loading history...
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