@@ -21,13 +21,19 @@ class LocalizedUniqueSlugField(LocalizedAutoSlugField):
21
21
When in doubt, use this over :see:LocalizedAutoSlugField.
22
22
Inherit from :see:AtomicSlugRetryMixin in your model to
23
23
make this field work properly.
24
+
25
+ By default, this creates a new slug if the field(s) specified
26
+ in `populate_from` are changed. Set `immutable=True` to get
27
+ immutable slugs.
24
28
"""
25
29
26
30
def __init__ (self , * args , ** kwargs ):
27
31
"""Initializes a new instance of :see:LocalizedUniqueSlugField."""
28
32
29
33
kwargs ["uniqueness" ] = kwargs .pop ("uniqueness" , get_language_codes ())
30
34
35
+ self .immutable = kwargs .pop ("immutable" , False )
36
+
31
37
super (LocalizedUniqueSlugField , self ).__init__ (* args , ** kwargs )
32
38
33
39
self .populate_from = kwargs .pop ("populate_from" )
@@ -42,6 +48,10 @@ def deconstruct(self):
42
48
43
49
kwargs ["populate_from" ] = self .populate_from
44
50
kwargs ["include_time" ] = self .include_time
51
+
52
+ if self .immutable is True :
53
+ kwargs ["immutable" ] = self .immutable
54
+
45
55
return name , path , args , kwargs
46
56
47
57
def pre_save (self , instance , add : bool ):
@@ -76,10 +86,14 @@ def pre_save(self, instance, add: bool):
76
86
77
87
slug = slugify (value , allow_unicode = True )
78
88
89
+ current_slug = getattr (instance , self .name ).get (lang_code )
90
+ if current_slug and self .immutable :
91
+ slugs .set (lang_code , current_slug )
92
+ continue
93
+
79
94
# verify whether it's needed to re-generate a slug,
80
95
# if not, re-use the same slug
81
96
if instance .pk is not None :
82
- current_slug = getattr (instance , self .name ).get (lang_code )
83
97
if current_slug is not None :
84
98
current_slug_end_index = current_slug .rfind ("-" )
85
99
stripped_slug = current_slug [0 :current_slug_end_index ]
0 commit comments