• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

andrlik / django-quotes / 12003642854

25 Nov 2024 05:06AM UTC coverage: 98.843%. Remained the same
12003642854

Pull #159

github

web-flow
Merge 260df5066 into 338a53c87
Pull Request #159: Bump astral-sh/setup-uv from 3 to 4

769 of 778 relevant lines covered (98.84%)

3.95 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.88
/src/django_quotes/utils.py
1
#
2
# utils.py
3
#
4
# Copyright (c) 2024 Daniel Andrlik
5
# All rights reserved.
6
#
7
# SPDX-License-Identifier: BSD-3-Clause
8
#
9

10
from django.core.exceptions import ObjectDoesNotExist
4✔
11
from django.db.models import Model
4✔
12
from loguru import logger
4✔
13
from slugify import slugify
4✔
14

15

16
def generate_unique_slug_for_model(
4✔
17
    model_class: type[Model],
18
    text: str,
19
    slug_field: str | None = "slug",
20
    max_length_override: int | None = None,
21
) -> str:
22
    """
23
    Generate a unique slug for the given model.
24

25
    Args:
26
        model_class (Model): A class based upon ``django.db.models.Model``
27
        text (str): Text to convert to a slug.
28
        slug_field (str | None): The name of the slug field of the model.
29
        max_length_override (int | None): Maximum number of characters to use
30
            if not the same as what's defined in the slug field.
31
    Returns:
32
         (str): The generated slug.
33
    """
34
    unique_found: bool = False
4✔
35
    has_next: bool = False
4✔
36
    next_val: int = 0
4✔
37
    if not max_length_override:
4✔
38
        logger.debug("Setting max_length of slug from field definition.")
4✔
39
        max_length: int = model_class._meta.get_field(slug_field).max_length  # type: ignore
4✔
40
    else:
41
        logger.debug("User override value for max length of slug.")
4✔
42
        max_length = max_length_override
4✔
43
    slug = slugify(text, max_length=max_length)
4✔
44
    logger.debug(f"Base slug is set to '{slug}'.")
4✔
45
    while not unique_found:
4✔
46
        logger.debug(f"Testing uniqueness of slug '{slug}'...")
4✔
47
        try:
4✔
48
            model_class.objects.get(**{str(slug_field): slug})
4✔
49
        except ObjectDoesNotExist:
4✔
50
            logger.debug("Slug is unique!")
4✔
51
            unique_found = True
4✔
52
        if not unique_found:
4✔
53
            logger.debug("Slug is not unique yet.")
4✔
54
            next_val += 1
4✔
55
            if has_next:
4✔
56
                slug = slug[len(slug) - (len(str(next_val - 1)) - 1) :]
×
57
            if len(slug) >= max_length:
4✔
58
                slug = slug[: max_length - (len(str(next_val)) + 1)]
4✔
59
            slug = slug + f"-{next_val}"
4✔
60
            has_next = True
4✔
61
    return slug
4✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc