'DjangoCMS: How to check for uniqueness of a field in a plugin model (CMSPlugin)?
I build a djangoCMS plugin which contain a slug. I want this slug to be unique. Since djangoCMS store page content in draft and public versions (with a copy of plugins data), I can't do it at database level because it is normal two have at two plugins (draft and public versions) with the same slug. I'm pretty sure there is an idiom for this but can't find it.
I've tried to make a check in the clean method of the model, but I can't access instance.placeholder which is None when being in clean method…
class MyPlugin(CMSPlugin):
slug = models.SlugField(
verbose_name=_("Slug"),
db_index=True,
max_length=255,
)
Any idea ?
Solution 1:[1]
I think I've found a solution by excluding objects where page is not draft:
def clean(self, *args, **kwargs):
sames_slug = MyPlugin.objects.filter(slug=self.slug).exclude(
placeholder__page__publisher_is_draft=False
)
if self.pk:
sames_slug = sames_slug.exclude(pk=self.pk)
if sames_slug.exists():
raise ValidationError(
{"slug": "There is already one with the same slug"}
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | fabien-michel |
