In Django saving a (translated) slug and making it unique doesn't work
I use Django 1.11 and the parler plugin for translation. Every time I save a slug, I wish to
- test if it already exists
- truncate the slug
- add number
- test again, if the new slug exists and so on
This way, I wish to create a unique slug on saving.
models.py:
from parler.models import TranslatableModel
from django.utils.translation import gettext_lazy as _
class Event(TranslatableModel):
translations = TranslatedFields(
event_title=models.CharField(_("event title"), max_length=512),
slug=models.SlugField(_("slug"), help_text=_("Used in the URL of the event page.")),
description=RichTextUploadingField(blank=True),
meta={'unique_together': (('language_code', 'slug'),)},
)
def save_translation(self, translation, *args, **kwargs):
"""Create a unique slug of 45 Characters + a dash and 4 digits."""
translation.slug = translation.slug[:50]
if Event.objects.active_translations(slug=translation.slug).exists():
# This is true on the first test for no apparent reason.
i = 0
while Event.objects.active_translations(slug=translation.slug).exists():
translation.slug = translation.slug[:44]+'-'+str(i)
i += 1
super(Event, self).save_translation(translation, *args, **kwargs)
This code dosen't work. It always add a number to the slug, no matter what, even if I enter a completely new slug.
django django-models django-parler
add a comment |
I use Django 1.11 and the parler plugin for translation. Every time I save a slug, I wish to
- test if it already exists
- truncate the slug
- add number
- test again, if the new slug exists and so on
This way, I wish to create a unique slug on saving.
models.py:
from parler.models import TranslatableModel
from django.utils.translation import gettext_lazy as _
class Event(TranslatableModel):
translations = TranslatedFields(
event_title=models.CharField(_("event title"), max_length=512),
slug=models.SlugField(_("slug"), help_text=_("Used in the URL of the event page.")),
description=RichTextUploadingField(blank=True),
meta={'unique_together': (('language_code', 'slug'),)},
)
def save_translation(self, translation, *args, **kwargs):
"""Create a unique slug of 45 Characters + a dash and 4 digits."""
translation.slug = translation.slug[:50]
if Event.objects.active_translations(slug=translation.slug).exists():
# This is true on the first test for no apparent reason.
i = 0
while Event.objects.active_translations(slug=translation.slug).exists():
translation.slug = translation.slug[:44]+'-'+str(i)
i += 1
super(Event, self).save_translation(translation, *args, **kwargs)
This code dosen't work. It always add a number to the slug, no matter what, even if I enter a completely new slug.
django django-models django-parler
add a comment |
I use Django 1.11 and the parler plugin for translation. Every time I save a slug, I wish to
- test if it already exists
- truncate the slug
- add number
- test again, if the new slug exists and so on
This way, I wish to create a unique slug on saving.
models.py:
from parler.models import TranslatableModel
from django.utils.translation import gettext_lazy as _
class Event(TranslatableModel):
translations = TranslatedFields(
event_title=models.CharField(_("event title"), max_length=512),
slug=models.SlugField(_("slug"), help_text=_("Used in the URL of the event page.")),
description=RichTextUploadingField(blank=True),
meta={'unique_together': (('language_code', 'slug'),)},
)
def save_translation(self, translation, *args, **kwargs):
"""Create a unique slug of 45 Characters + a dash and 4 digits."""
translation.slug = translation.slug[:50]
if Event.objects.active_translations(slug=translation.slug).exists():
# This is true on the first test for no apparent reason.
i = 0
while Event.objects.active_translations(slug=translation.slug).exists():
translation.slug = translation.slug[:44]+'-'+str(i)
i += 1
super(Event, self).save_translation(translation, *args, **kwargs)
This code dosen't work. It always add a number to the slug, no matter what, even if I enter a completely new slug.
django django-models django-parler
I use Django 1.11 and the parler plugin for translation. Every time I save a slug, I wish to
- test if it already exists
- truncate the slug
- add number
- test again, if the new slug exists and so on
This way, I wish to create a unique slug on saving.
models.py:
from parler.models import TranslatableModel
from django.utils.translation import gettext_lazy as _
class Event(TranslatableModel):
translations = TranslatedFields(
event_title=models.CharField(_("event title"), max_length=512),
slug=models.SlugField(_("slug"), help_text=_("Used in the URL of the event page.")),
description=RichTextUploadingField(blank=True),
meta={'unique_together': (('language_code', 'slug'),)},
)
def save_translation(self, translation, *args, **kwargs):
"""Create a unique slug of 45 Characters + a dash and 4 digits."""
translation.slug = translation.slug[:50]
if Event.objects.active_translations(slug=translation.slug).exists():
# This is true on the first test for no apparent reason.
i = 0
while Event.objects.active_translations(slug=translation.slug).exists():
translation.slug = translation.slug[:44]+'-'+str(i)
i += 1
super(Event, self).save_translation(translation, *args, **kwargs)
This code dosen't work. It always add a number to the slug, no matter what, even if I enter a completely new slug.
django django-models django-parler
django django-models django-parler
asked Nov 18 '18 at 11:27
mogohmogoh
3021218
3021218
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
The problem here is that save_translation gets called multiple times. My solution is:
def save_translation(self, translation, *args, **kwargs):
"""Create a unique slug build of the title + language code + a number."""
translation.slug = translation.slug[:50]
"""
This filter is a bit more complicated.
If the same slug but with a differen ID alread exists:
~Q(id=translation.master_id) &
Q(translations__slug=translation.slug)
Or if the same slug with the same ID but different language already exists:
Q(id=translation.master_id) &
~Q(translations__language_code=translation.language_code) &
Q(translations__slug=translation.slug)
"""
if Event.objects.filter(
(~Q(id=translation.master_id) &
Q(translations__slug=translation.slug)) |
(Q(id=translation.master_id) &
~Q(translations__language_code=translation.language_code) &
Q(translations__slug=translation.slug))
).exists():
i = 1
while Event.objects.filter(
(~Q(id=translation.master_id) &
Q(translations__slug=translation.slug)) |
(Q(id=translation.master_id) &
~Q(translations__language_code=translation.language_code) &
Q(translations__slug=translation.slug))
).exists():
# Truncate the slug, if it is too long. This happens, if the
# initial slug is to long or if the trailing number reaches
# another digit.
trunc_number = (4 + ceil(log10(i + 1)))
if len(translation.slug) + trunc_number > 50:
translation.slug = translation.slug[:50-trunc_number]
# Substitute the trailing language code and number with a bigger number.
translation.slug = re.sub(
r'(?P<slug_start>.*?)(-(de|en))?(-(d)+)?$',
'g<slug_start>' + '-' + translation.language_code + '-' + str(i),
translation.slug)
i += 1
super(Event, self).save_translation(translation, *args, **kwargs)
It got a bit longer then I hoped, but I think it works.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53360328%2fin-django-saving-a-translated-slug-and-making-it-unique-doesnt-work%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
The problem here is that save_translation gets called multiple times. My solution is:
def save_translation(self, translation, *args, **kwargs):
"""Create a unique slug build of the title + language code + a number."""
translation.slug = translation.slug[:50]
"""
This filter is a bit more complicated.
If the same slug but with a differen ID alread exists:
~Q(id=translation.master_id) &
Q(translations__slug=translation.slug)
Or if the same slug with the same ID but different language already exists:
Q(id=translation.master_id) &
~Q(translations__language_code=translation.language_code) &
Q(translations__slug=translation.slug)
"""
if Event.objects.filter(
(~Q(id=translation.master_id) &
Q(translations__slug=translation.slug)) |
(Q(id=translation.master_id) &
~Q(translations__language_code=translation.language_code) &
Q(translations__slug=translation.slug))
).exists():
i = 1
while Event.objects.filter(
(~Q(id=translation.master_id) &
Q(translations__slug=translation.slug)) |
(Q(id=translation.master_id) &
~Q(translations__language_code=translation.language_code) &
Q(translations__slug=translation.slug))
).exists():
# Truncate the slug, if it is too long. This happens, if the
# initial slug is to long or if the trailing number reaches
# another digit.
trunc_number = (4 + ceil(log10(i + 1)))
if len(translation.slug) + trunc_number > 50:
translation.slug = translation.slug[:50-trunc_number]
# Substitute the trailing language code and number with a bigger number.
translation.slug = re.sub(
r'(?P<slug_start>.*?)(-(de|en))?(-(d)+)?$',
'g<slug_start>' + '-' + translation.language_code + '-' + str(i),
translation.slug)
i += 1
super(Event, self).save_translation(translation, *args, **kwargs)
It got a bit longer then I hoped, but I think it works.
add a comment |
The problem here is that save_translation gets called multiple times. My solution is:
def save_translation(self, translation, *args, **kwargs):
"""Create a unique slug build of the title + language code + a number."""
translation.slug = translation.slug[:50]
"""
This filter is a bit more complicated.
If the same slug but with a differen ID alread exists:
~Q(id=translation.master_id) &
Q(translations__slug=translation.slug)
Or if the same slug with the same ID but different language already exists:
Q(id=translation.master_id) &
~Q(translations__language_code=translation.language_code) &
Q(translations__slug=translation.slug)
"""
if Event.objects.filter(
(~Q(id=translation.master_id) &
Q(translations__slug=translation.slug)) |
(Q(id=translation.master_id) &
~Q(translations__language_code=translation.language_code) &
Q(translations__slug=translation.slug))
).exists():
i = 1
while Event.objects.filter(
(~Q(id=translation.master_id) &
Q(translations__slug=translation.slug)) |
(Q(id=translation.master_id) &
~Q(translations__language_code=translation.language_code) &
Q(translations__slug=translation.slug))
).exists():
# Truncate the slug, if it is too long. This happens, if the
# initial slug is to long or if the trailing number reaches
# another digit.
trunc_number = (4 + ceil(log10(i + 1)))
if len(translation.slug) + trunc_number > 50:
translation.slug = translation.slug[:50-trunc_number]
# Substitute the trailing language code and number with a bigger number.
translation.slug = re.sub(
r'(?P<slug_start>.*?)(-(de|en))?(-(d)+)?$',
'g<slug_start>' + '-' + translation.language_code + '-' + str(i),
translation.slug)
i += 1
super(Event, self).save_translation(translation, *args, **kwargs)
It got a bit longer then I hoped, but I think it works.
add a comment |
The problem here is that save_translation gets called multiple times. My solution is:
def save_translation(self, translation, *args, **kwargs):
"""Create a unique slug build of the title + language code + a number."""
translation.slug = translation.slug[:50]
"""
This filter is a bit more complicated.
If the same slug but with a differen ID alread exists:
~Q(id=translation.master_id) &
Q(translations__slug=translation.slug)
Or if the same slug with the same ID but different language already exists:
Q(id=translation.master_id) &
~Q(translations__language_code=translation.language_code) &
Q(translations__slug=translation.slug)
"""
if Event.objects.filter(
(~Q(id=translation.master_id) &
Q(translations__slug=translation.slug)) |
(Q(id=translation.master_id) &
~Q(translations__language_code=translation.language_code) &
Q(translations__slug=translation.slug))
).exists():
i = 1
while Event.objects.filter(
(~Q(id=translation.master_id) &
Q(translations__slug=translation.slug)) |
(Q(id=translation.master_id) &
~Q(translations__language_code=translation.language_code) &
Q(translations__slug=translation.slug))
).exists():
# Truncate the slug, if it is too long. This happens, if the
# initial slug is to long or if the trailing number reaches
# another digit.
trunc_number = (4 + ceil(log10(i + 1)))
if len(translation.slug) + trunc_number > 50:
translation.slug = translation.slug[:50-trunc_number]
# Substitute the trailing language code and number with a bigger number.
translation.slug = re.sub(
r'(?P<slug_start>.*?)(-(de|en))?(-(d)+)?$',
'g<slug_start>' + '-' + translation.language_code + '-' + str(i),
translation.slug)
i += 1
super(Event, self).save_translation(translation, *args, **kwargs)
It got a bit longer then I hoped, but I think it works.
The problem here is that save_translation gets called multiple times. My solution is:
def save_translation(self, translation, *args, **kwargs):
"""Create a unique slug build of the title + language code + a number."""
translation.slug = translation.slug[:50]
"""
This filter is a bit more complicated.
If the same slug but with a differen ID alread exists:
~Q(id=translation.master_id) &
Q(translations__slug=translation.slug)
Or if the same slug with the same ID but different language already exists:
Q(id=translation.master_id) &
~Q(translations__language_code=translation.language_code) &
Q(translations__slug=translation.slug)
"""
if Event.objects.filter(
(~Q(id=translation.master_id) &
Q(translations__slug=translation.slug)) |
(Q(id=translation.master_id) &
~Q(translations__language_code=translation.language_code) &
Q(translations__slug=translation.slug))
).exists():
i = 1
while Event.objects.filter(
(~Q(id=translation.master_id) &
Q(translations__slug=translation.slug)) |
(Q(id=translation.master_id) &
~Q(translations__language_code=translation.language_code) &
Q(translations__slug=translation.slug))
).exists():
# Truncate the slug, if it is too long. This happens, if the
# initial slug is to long or if the trailing number reaches
# another digit.
trunc_number = (4 + ceil(log10(i + 1)))
if len(translation.slug) + trunc_number > 50:
translation.slug = translation.slug[:50-trunc_number]
# Substitute the trailing language code and number with a bigger number.
translation.slug = re.sub(
r'(?P<slug_start>.*?)(-(de|en))?(-(d)+)?$',
'g<slug_start>' + '-' + translation.language_code + '-' + str(i),
translation.slug)
i += 1
super(Event, self).save_translation(translation, *args, **kwargs)
It got a bit longer then I hoped, but I think it works.
answered Nov 21 '18 at 15:17
mogohmogoh
3021218
3021218
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53360328%2fin-django-saving-a-translated-slug-and-making-it-unique-doesnt-work%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown