Skip to content

Commit 88032d2

Browse files
committed
Add max length checking
As we are appending data to the end of a slug it adds additional length to the slug. This can mean we have gone past the fields length causing database errors. As we are passing a manager and the field name into the function we can determine the maximum length of the field and limit the slug to that length.
1 parent 0b64728 commit 88032d2

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

forms_builder/forms/utils.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,16 @@ def unique_slug(manager, slug_field, slug):
2727
Ensure slug is unique for the given manager, appending a digit
2828
if it isn't.
2929
"""
30+
max_length = manager.model._meta.get_field(slug_field).max_length
31+
slug = slug[:max_length]
3032
i = 0
3133
while True:
3234
if i > 0:
3335
if i > 1:
3436
slug = slug.rsplit("-", 1)[0]
35-
slug = "%s-%s" % (slug, i)
37+
# We need to keep the slug length under the slug fields max length. We need to
38+
# account for the length that is added by adding a random integer and `-`.
39+
slug = "%s-%s" % (slug[:max_length - len(str(i)) - 1], i)
3640
if not manager.filter(**{slug_field: slug}):
3741
break
3842
i += 1

0 commit comments

Comments
 (0)