How to avoid IntegrityError and avoid db colision when saving model after sanitize slug with slugify?

I am currently working on a simple web project, where I have several models that make use of SlugField as URL, such as Page, Note and Tag. From the admin panel the user can edit the slug and other fields of the model.

The user can modify the slug manually to make it more user friendly.

The user can also enter content in uppercase, and special characters, either by mistake or by malpractice.

The validation of the slug as a unique field is done correctly in the frontend if it is entered correctly, but not if uppercase characters or special characters are entered.

Here is an example:

User creates a new tag with slug: new-tag
Hit save, and it does the work.

User creates a new tag with slug new-tag
Hit save, and the user get a front end validation warning, saying is not possible.
Ok, as expected.

User creates a new tag with slug: New-Tag(noticed the capital letters)
Hit save and we got.

  • Exception Type: IntegrityError
  • Exception Value: UNIQUE constraint failed: notes_tag.slug
    Which is expected and im trying to address it.

This is my model: You can check full project here: Github repo


class Tag(models.Model):
    id = models.UUIDField(default=uuid.uuid4, unique=True,
                          primary_key=True, editable=False)
    name = models.CharField(max_length=255)
    slug = models.SlugField(unique=True)

    def save(self, *args, **kwargs):
        # todo: check colision with others URLs
        self.slug = slugify(self.slug)
        super(Tag, self).save(*args, **kwargs)

My first approach to solve the colision:

def save(self, *args, **kwargs):
        self.slug = slugify(self.slug)
        original_slug = self.slug
        queryset = Tag.objects.filter(slug=self.slug).exists()
        counter = 1
        while queryset:
            self.slug = f"{original_slug}-{counter}"
            counter += 1
            queryset = Tag.objects.filter(slug=self.slug).exists()
        super(Tag, self).save(*args, **kwargs)

For me it doesnt seem like they way it should be , to check the database with a while loop cool be dangerous. But ok, i didt like this and the problem is this save method is executing always, with new items creation and with updates.

I try to use if self.id to check if is new item or just updated but as my Model override the id field, by the time the execution reach the save method the item as already been created and got an id.

So, any recommendation on that issue? Any way to follow?

My guess is that might be a simplier solution to validate the slug after slugify and use the same front end warning is built in with django.

But im wonder why self.id exist once the execution reach the save method…?

I already check:

  • override the save method in django
  • https://www.geeksforgeeks.org/overriding-the-save-method-django-models/

Thanks in advance.

I try to check if entity already exist in database, then add a ‘-number’ at the end of the slug, but cannot check whether a item is create or update so the addition of the ‘-number’ is happening evertyhing after i hit save.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật